I l @ ve RuBoard |
Using Properties in Your C++ ClassesProperties are pseudo-data members of your classes. They are accessed just like public data members but in reality they are functions within the class. Adding properties to Garbage Collected C++ classes is accomplished by the use of the __property keyword. Listing 1.4.14 shows a simple GC class with properties. Listing 1.4.14 props.cpp : Simple Properties in a GC Class#using <mscorlib.dll> using namespace System; using namespace System::IO; __gc class PropClass { int m_x; int m_y; int m_z; public: PropClass() : m_y(19762), m_z(3860) { } // read / write properties for a data member __property int get_x(){ return m_x;} __property void set_x(int v){ m_x=v;} // read only properties for a data member __property int get_y(){ return m_y;} // write only properties for a data member __property void set_z(int v){ m_z=v;} // properties that don't act on data at-all __property int get_bogus() { Console::WriteLine("Read the bogus property!"); return 10; } __property void set_bogus(int v) { Console::WriteLine("Wrote { 0} to the bogus property!",__box(v)); } String* ToString() { StringWriter *w=new StringWriter(); w->Write("PropClass; m_x = { 0} , m_y = { 1} , m_z = { 2} ",__ box(m_x), __ The props.cpp program shows properties that directly access data members within a class and properties that perform some computation that is not necessarily related to class attributes at all. The program also shows the technique of creating read-only or write-only properties. To create a read-only property, simply include only the get_ accessor. Write-only properties have only set_ accessors. Finally, the program shows the interesting technique of overriding the ToString() method. Remember that classes declared with __gc are derived implicitly from System::Object . This class defines the ToString method, which is used to output a text representation of the class to text streams. |
I l @ ve RuBoard |