构造函数初始化列表的顺序
证明了
1. 先初始化基类再初始化成员,在初始化列表初始类成员是类的,可以减少构造次数
2. 类成员是一个类是栈方式存储自动释放,指针类需手动释放
//类A
#include "A.h"
A::A(void)
{
cout<< "create A"<<endl;
}
A::A(int x)
{
cout<< "create A(x)"<<endl;
}
A::A(const A& a)
{
cout<< "copy create A(a)"<<endl;
}
A::~A(void)
{
cout<<"delete A"<<endl;
}
//类Bass
#include "Bass.h"
Bass::Bass(void)
{
cout<< "create Bass"<<endl;
}
Bass::~Bass(void)
{
cout<<"delete Bass"<<endl;
}
//类Sub 继承类Bass
class Sub:public Bass
{
public:
A b;
A a;
A *pa;
Sub(void);
Sub(A &a);
virtual~Sub(void);
};
#include "Sub.h"
Sub::Sub(void)
{
cout<<"create Sub"<<endl;
}
Sub::Sub(A &a):a(1),b(a)
{
cout<<"create Sub"<<endl;
}
Sub::~Sub(void)
{
cout<<"delete Sub"<<endl;
}
//主函数类main
void fun()
{
A a;
cout<<"==="<<endl;
Sub b(a);
}
int main()
{
fun();
return 0;
}
输出结果
create A
==
create Bass
copy create A(a)
create A(x)
create Sub
delete Sub
delete A
delete A
delete Bass
delete A