| using namespace System; using namespace System::Collections; void PrintEntries(String^ s, ArrayList^ aList); int main() { ArrayList^ al1 = gcnew ArrayList; /*1*/ al1->Add("Red"); al1->Add("Blue"); al1->Add("Green"); al1->Add("Yellow"); /*2*/ PrintEntries("al1", al1); /*3*/ ArrayList^ al2 = static_cast<ArrayList^>(al1->Clone()); /*4*/ PrintEntries("al2", al2); /*5*/ al1->Remove("Blue"); al1->Add("Black"); al1->RemoveAt(0); al1->Insert(0, "Brown"); /*6*/ PrintEntries("al1", al1); /*7*/ PrintEntries("al2", al2); } void PrintEntries(String^ s, ArrayList^ aList) : ", s); for each(Object^ o in aList) ", o); } Console::WriteLine(); } |
| al1: Red Blue Green Yellow al2: Red Blue Green Yellow al1: Brown Green Yellow Black al2: Red Blue Green Yellow |
| public ref class Point : ICloneable { // ... public: virtual Object^ Clone() { return MemberwiseClone(); } }; int main() { /*1*/ Point^ p1 = gcnew Point(3, 5); /*2*/ Console::WriteLine("p1: ", p1); /*3*/ Point^ p2 = static_cast<Point^>(p1->Clone()); /*4*/ p1->Move(9, 11); /*5*/ Console::WriteLine("p1: ", p1); /*6*/ Console::WriteLine("p2: ", p2); } |
| p1: (3,5) p1: (9,11) p2: (3,5) |
| protected: Object^ MemberwiseClone(); |
| x->MemberwiseClone() != x x->MemberwiseClone()->GetType() == x->GetType() |
| using namespace System; public ref class Circle : ICloneable { Point^ origin; float radius; public: property Point^ Origin { Point^ get() { return static_cast<Point^>(origin->Clone()); } } void SetOrigin(int x, int y) { origin->X = x; origin->Y = y; } void SetOrigin(Point^ p) { SetOrigin(p->X, p->Y); } property double Radius { double get() { return radius; } void set(double value) { radius = static_cast<float>(value); } } Circle() { origin = gcnew Point; SetOrigin(0, 0); Radius = 0.0; } Circle(int x, int y, double r) { origin = gcnew Point; SetOrigin(x, y); Radius = r; } Circle(Point^ p, double r) { origin = gcnew Point; SetOrigin(p->X, p->Y); Radius = r; } virtual String^ ToString() override { return String::Concat("{", Origin, ",", Radius, "}"); } virtual Object^ Clone() { /*1*/ Circle^ c = static_cast<Circle^>(MemberwiseClone()); /*2*/ c->origin = static_cast<Point^>(origin->Clone()); /*3*/ return c; } }; |
| int main() { /*1*/ Circle^ c1 = gcnew Circle(5, 9, 1.5); /*2*/ Console::WriteLine("c1: ", c1); /*3*/ Circle^ c2 = static_cast<Circle^>(c1->Clone()); /*4*/ Point^ p = c1->Origin; /*5*/ Console::WriteLine(" p: ", p); /*6*/ c1->SetOrigin(9, 11); /*7*/ Console::WriteLine("c1: ", c1); /*8*/ Console::WriteLine(" p: ", p); /*9*/ Console::WriteLine("c2: ", c2); } |
用户评论