扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:谢启东编译 来源:天极开发 2007年11月14日
关键字:
generic <typename T> public ref class Vector { int length; /*1*/ array<T>^ vector; public: virtual Object^ Clone() { Vector<T>^ v = static_cast<Vector<T>^>(MemberwiseClone()); v->vector = static_cast<array<T>^>(vector->Clone()); return v; } }; int main() { /*1*/ Vector<int>^ v1 = gcnew Vector<int>(5, 7); /*2*/ Console::WriteLine("v1: {0}", v1); /*3*/ Vector<int>^ v2 = static_cast<Vector<int>^>(v1->Clone()); /*4*/ Console::WriteLine("v2: {0}", v2); /*5*/ v1[0] = 3; /*6*/ v1[3] = 9; /*7*/ v2[4] = 1; /*8*/ Console::WriteLine("v1: {0}", v1); /*9*/ Console::WriteLine("v2: {0}", v2); } |
public ref class Base : ICloneable { array<int>^ bPair ; public: Base(int i, int j) { bPair = gcnew array<int>(2) {i, j}; } void SetValue(int i, int j) { bPair[0] = i; bPair[1] = j; } virtual String^ ToString() override { return String::Concat("[", bPair[0], ":", bPair[1], "]"); } virtual Object^ Clone() override { Base^ b = static_cast<Base^>(MemberwiseClone()); b->bPair = static_cast<array<int>^>(bPair->Clone()); return b; } }; |
using namespace System; public ref class Derived : Base, ICloneable { array<int>^ dPair; public: Derived(int bi, int bj, int i, int j) : Base(bi, bj) { dPair = gcnew array<int>(2) {i, j}; } void SetValue(int bi, int bj, int i, int j) { Base::SetValue(bi, bj); dPair[0] = i; dPair[1] = j; } virtual String^ ToString() override { return String::Concat("[{", Base::ToString(), "}", dPair[0], ":", dPair[1], "]"); } virtual Object^ Clone() override { // Derived^ d = static_cast<Derived^>(Base::MemberwiseClone()); Derived^ d = static_cast<Derived^>(Base::Clone()); d->dPair = static_cast<array<int>^>(dPair->Clone()); return d; } }; |
int main() { Derived^ d1 = gcnew Derived(10, 20, 30, 40); Console::WriteLine("d1 = {0}", d1); Derived^ d2 = static_cast<Derived^>(d1->Clone()); Console::WriteLine("d2 = {0}", d2); d1->Base::SetValue(5, 6); Console::WriteLine("d1 = {0}", d1); Console::WriteLine("d2 = {0}", d2); } |
public ref class Test : ICloneable { int data; static int objectCount = 0; public: Test() { data = 0; ++objectCount; } Test(int value) { data = value; ++objectCount; } virtual String^ ToString() override { return String::Concat(data, ", ", objectCount); } virtual Object^ Clone() { /*1*/ Test^ copy = static_cast<Test^>(MemberwiseClone()); /*2*/ ++objectCount; return copy; } }; int main() { /*3*/ Test^ t1 = gcnew Test; Console::WriteLine("t1 using new: {0}", t1); /*4*/ Test^ t2 = static_cast<Test^>(t1->Clone()); Console::WriteLine("t2 using Clone: {0}", t2); /*5*/ Test^ t3 = gcnew Test(1); Console::WriteLine("t3 using new: {0}", t3); /*6*/ Test^ t4 = static_cast<Test^>(t3->Clone()); Console::WriteLine("t4 using Clone: {0}", t4); } } |
t1 using new: 0, 1 t2 using Clone: 0, 2 t3 using new: 1, 3 t4 using Clone: 1, 4 |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者