gpt4 book ai didi

c++ - 继承和初始化顺序

转载 作者:行者123 更新时间:2023-11-30 01:42:38 24 4
gpt4 key购买 nike

考虑

 class A
{
};

class B
{
B(A * in);
};

class C : public A
{
B b;
public:
C():b(this){}
};

C 中的构造函数安全吗? A 的成员是否已经可用(并已构建)?

最佳答案

是的。在执行构造函数的其余部分之前构造所有基类。

例如,来自 Stroustrup C++ 2011 一书:

17.2.3 Base and Member Destructors
Constructors and destructors interact correctly with class hierarchies (§3.2.4, Chapter 20). A constructor
builds a class object ‘‘from the bottom up’’:
[1] first, the constructor invokes its base class constructors,
[2] then, it invokes the member constructors, and
[3] finally, it executes its own body.
A destructor ‘‘tears down’’ an object in the reverse order:
[1] first, the destructor executes its own body,
[2] then, it invokes its member destructors, and
[3] finally, it inv okes its base class destructors.

关于c++ - 继承和初始化顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39358607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com