一、整体代码
01.cpp
#include <iostream>
using namespace std;
class ObjectB
{
public:
ObjectB(int objb) : objb_(objb)
{
cout<<"ObjectB ..."<<endl;
}
~ObjectB()
{
cout<<"~ObjectB ..."<<endl;
}
int objb_;
};
class ObjectD
{
public:
ObjectD(int objd) : objd_(objd)
{
cout<<"ObjectD ..."<<endl;
}
~ObjectD()
{
cout<<"~ObjectD ..."<<endl;
}
int objd_;
};
class Base
{
public:
Base(int b) : b_(b), objb_(111)
{
cout<<"Base ..."<<endl;
}
Base(const Base& other) : objb_(other.objb_), b_(other.b_)
{
cout<<"Base ...copy"<<endl;
}
~Base()
{
cout<<"~Base ..."<<endl;
}
int b_;
ObjectB objb_;
};
class Derived : public Base
{
public:
Derived(int b, int d) : d_(d), Base(b), objd_(222)
{
cout<<"Derived ..."<<endl;
}
Derived(const Derived& other) : d_(other.d_), objd_(other.objd_), Base(other)//调用了父类的拷贝构造函数
{
cout<<"Derived ...copy"<<endl;
}
~Derived()//先执行方法体,再调用父类的析构函数
{
cout<<"~Derived ..."<<endl;
}
int d_;
ObjectD objd_;
};
int main(void)
{
Derived d(100, 200);//首先调用父类的objb_(111),然后是父类构造函数,之后是子类的objd_(222),最后是子类的构造函数
//cout<<d.b_<<" "<<d.d_<<endl;
//Base b1(100);//调用父类的构造函数
//Base b2(b1);//调用父类拷贝构造函数
//cout<<b2.b_<<endl;
//Derived d2(d);//调用子类拷贝构造函数
return 0;
}
ObjectB ...
Base ...
ObjectD ...
Derived ...
~Derived ...//先析构对象
~ObjectD ...//再析构对象中的成员对象
~Base ...
~ObjectB ..