using namespace System; public value class Point { int x; int y; public: //定义属性X与 Y的读写实例 property int X { int get() { return x; } void set(int val) { x = val; } } property int Y { int get() { return y; } void set(int val) { y = val; } } //定义实例构造函数
Point(int xor, int yor) { X = xor; Y = yor; } void Move(int xor, int yor) { X = xor; Y = yor; } virtual bool Equals(Object^ obj) override { if (obj == nullptr) { return false; } if (GetType() == obj->GetType()) { Point^ p = static_cast<Point^>(obj); return (X == p->X) && (Y == p->Y); } return false; } static bool Operator==(Point p1, Point p2) { return (p1.X == p2.X) && (p1.Y == p2.Y); } // static bool operator==(Point% p1, Point% p2) // { // return (p1.X == p2.X) && (p1.Y == p2.Y); // }
value class X sealed {/*...*/}; 请注重,此处没有默认的构造函数。对一个值类来说,CLI本身把类实例中所有字段的位都设置为零,所以,不能提供自己的默认构造函数;然而,零、false、nullptr对其他类型来说,也许并不是合适的默认值,因此,对某些特定类型来说,就要用引用类型来取代值类型了。(遵从C++/CLI的实现会将false与nullptr表示为位全部为零。)
Console::WriteLine("p2 is {0}", p2); Point% p4 = p3;
Point p5 = p2; p5 = p2;
Console::WriteLine("p1 == p2 is {0}", p1 == p2); Console::WriteLine("p1.Equals(p2) is {0}", p1.Equals(p2)); } p2 is (3,4) p1 == p2 is False p1.Equals(p2) is False 在第一次调用Console::WriteLine时,用传值的方式传递进一个Point,但是,这个函数却指望着接受一个对象引用,在此,Point值被自动装箱,并把装箱后的对象引用传递给函数。
C++/CLI类型CLI值类型boolSystem::Booleanwchar_tSystem::Charsigned charSystem::SByteunsigned charSystem::BytecharSystem::SByte或 System::Byteshort intSystem::Int16unsigned short intSystem::UInt16int System::Int32unsigned intSystem::UInt32long long intSystem::Int64unsigned long long intSystem::UInt64floatSystem::SingledoubleSystem::Double 表1:C++/CLI与CLI值类的映射关系