class ABase
{
public:
ABase():Aval(10) { cout<<"construct ABase!"<<endl; }
~ABase() { cout<<"destory ABase!"<<endl; }
protected:
int Aval;
};
class CBase
{
public:
CBase(ABase &at):a(at)
{
cout<<"construct CBase!"<<endl;
}
~CBase()
{
cout<<"destory CBase!"<<endl;
}
private:
int Cval;
ABase a;
};
int main()
{
ABase aa;
CBase bb(aa);
return 0;
}
输出结果是什么?为什么?
如果把类CBase的构造函数改成如下:
CBase(ABase &at)
{
a = at;
cout<<"construct CBase!"<<endl;
}
输出结果是什么?并说明原因?
construct ABase!
construct CBase!
destroy CBase!
destroy ABase!
destroy ABase!
然后改成a = at;结果是:
construct ABase!
construct ABase!
construct CBase!
destroy CBase!
destroy ABase!
destroy Abase!
CBase(ABase &at):a(at)
{
。。。
}
指明了调用a的copy constructor
CBase(ABase &at)
{
a = at;
cout<<"construct CBase!"<<endl;
}
构造函数等效于
CBase(ABase &at) : a()
{
a = at;
cout<<"construct CBase!"<<endl;
}
构造函数 & 析构函数
最新推荐文章于 2022-05-19 23:06:29 发布