类的构造顺序

本文探讨了C++中不同类(A、B、C)构造与析构的顺序,尤其是在继承关系下如何影响对象的创建与销毁过程。通过具体实例展示了基类与派生类、成员对象在构造函数调用时的执行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class C
{
public:
C()
{
cout << "C constructor" << endl;
}
~C()
{
cout << "C destroy" << endl;
}
C(C &c)
{
cout << "C copy" << endl;
}

protected:
private:
};

class A
{
public:
A()
{
cout << "A constructor" << endl;
}
~A()
{
cout << "A destroy" << endl;
}
A(A &a)
{
cout << "A Copy" << endl;
}
virtual void Test()
{
cout << "Call A" << endl;
}
protected:
private:
//C c;
};

class B : public A
{
public:
B()
{
cout << "B constructor" << endl;
}
~B()
{
cout << "B destroy" << endl;
}
B(B &b)
{
cout << "B Copy" << endl;
}
void Test()
{
cout << "Call B" << endl;
}
protected:
private:
C c;
};
int main(int argc, _TCHAR* argv[])
{
B b;
return 0;
}

C 在父类A中构造顺序为
C constructor
A constructor
B constructor
B destroy
A destroy
C destroy
C 在子类B中构造顺序为
A constructor
C constructor
B constructor
B destroy
C destroy
A destroy
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值