转自:http://blog.csdn.net/daheiantian/article/details/6438782
Code:
#include <iostream> using namespace std; class A { public: A() { cout<<"int A::A()"<<endl; } A(A &a) { cout<<"int A::A(A &a)"<<endl; } A& operator=(A& a) { cout<<"int A::operator=(A &a)"<<endl; return a; } virtual ~A() { cout<<"int A::~A()"<<endl; } }; class M :public A { public: M() { cout<<"int M::M()"<<endl; } M(M &a) { cout<<"int M::M(M &a)"<<endl; } M& operator=(M& m) { cout<<"int M::operator=(M &a)"<<endl; return m; } virtual ~M() { cout<<"int M::~M()"<<endl; } }; class B:virtual public M { public: B() { cout<<"int B::B()"<<endl; } B(B &a) { cout<<"int B::B(B &a)"<<endl; } B& operator=(B& b) { cout<<"int B::operator=(B &a)"<<endl; return b; } virtual ~B() { cout<<"int B::~B()"<<endl; } }; class N :public A { public: N() { cout<<"int N::N()"<<endl; } N(N &a) { cout<<"int N::N(N &a)"<<endl; } N& operator=(N& n) { cout<<"int N::operator=(N &a)"<<endl; return n; } virtual ~N() { cout<<"int N::~N()"<<endl; } }; class C:virtual public N { public: C() { cout<<"int C::C()"<<endl; } C(C &a) { cout<<"int C::C(C &a)"<<endl; } C& operator=(C& c) { cout<<"int C::operator=(C &a)"<<endl; return c; } virtual ~C() { cout<<"int C::~C()"<<endl; } }; class E:virtual public M{ public: E() { cout<<"int E::E()"<<endl; } E(E &a) { cout<<"int E::E(E &a)"<<endl; } E& operator=(E& e) { cout<<"int E::operator=(E &a)"<<endl; return e; } virtual ~E() { cout<<"int E::~E()"<<endl; } }; class D:public B, public C, public E { public: D() { cout<<"int D::D()"<<endl; } D(D &a) { cout<<"int D::D(D &a)"<<endl; } D& operator=(D& d) { cout<<"int D::operator=(D &a)"<<endl; return d; } virtual ~D() { cout<<"int D::~D()"<<endl; } }; int main(int argc, char **argv) { cout<<"-------构造函数-------"<<endl; D d; cout<<"-------复制构造函数-------"<<endl; D d1(d); cout<<"-------赋值操作符-------"<<endl; d = d1; cout<<"-------析构函数-------"<<endl; return 0; }
Result:
-------构造函数------- int A::A() int M::M()//构造虚基类M时,要先构造其父类A int A::A() int N::N()//和M一样,构造虚基类N时,也要先构造其父类A int B::B()//构造完虚基类,开始构造直接父类,按照声明顺序为B、C、E int C::C() int E::E() int D::D()//最后构造自己 -------复制构造函数------- int A::A() int M::M() int A::A() int N::N() int B::B() int C::C() int E::E() int D::D(D &a)//因为D中定义了复制构造函数,并且没有显式调用父类的构造函数,所以所有的“虚基类”和“直接父类”都调用默认构造函数 -------赋值操作符------- int D::operator=(D &a) //因为显式调用了赋值操作符,那么就只调用自己的代码,不会隐式调用其它的函数 -------析构函数------- int D::~D() int E::~E() int C::~C() int B::~B() int N::~N() int A::~A() int M::~M() int A::~A()//因为main函数中定义了两个D对象,所以main函数结束时要进行析构两个D对象。析构的顺序与 构造函数相反。 int D::~D() int E::~E() int C::~C() int B::~B() int N::~N() int A::~A() int M::~M() int A::~A() Press any key to continue.
时间: 2024-12-29 12:00:50