1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
#include <iostream>
template<typename T>
struct Cloneable
{
virtual T *Clone() const
{
return new T(*dynamic_cast<const T*>(this));
}
protected:
Cloneable(){}
Cloneable(const Cloneable &){}
virtual Cloneable &operator=(const Cloneable &){ return*this; }
virtual ~Cloneable(){}
};
struct A : Cloneable<A>
{
A() : x(1) {}
A(const A &f) : x(f.x) {}
A(int v) : x(v) {}
virtual A &operator=(const A &f)
{
x = f.x;
return*this;
}
virtual void Print() const
{
std::cout << "x=" << x << std::endl;
}
virtual ~A(){}
private:
int x;
};
struct B : A, Cloneable<B>
{
B() : q(2) {}
B(const B &f) : A(f), q(f.q) {}
B(int v) : A(v-1), q(v) {}
virtual B &operator=(const B &f)
{
A::operator=(f);
q = f.q;
return*this;
}
virtual A &operator=(const A &f)
{
A::operator=(f);
const B *b = dynamic_cast<const B*>(&f);
if(b)
{
q = b->q;
}
return*this;
}
using Cloneable<B>::Clone;
virtual void Print() const
{
std::cout << "q=" << q << ", ";
A::Print();
}
~B(){}
private:
int q;
};
int main()
{
B b1 (7), b2, *b3 (0);
A &a1 (b1), &a2 (b2), *a3 (0);
b1.Print();
b2.Print();
a1.Print();
a2.Print();
b3 = b1.Clone();
b3->Print();
delete b3;
a3 = a1.Clone();
a3->Print();
delete a3;
b2 = b1;
b2.Print();
a3 = new B(9);
a2 = *a3;
a2.Print();
b2.Print();
}
|
q=7, x=6
q=2, x=1
q=7, x=6
q=2, x=1
q=7, x=6
x=6
q=7, x=6
q=9, x=8
q=9, x=8 |