gpt4 book ai didi

c++ - 派生类构造函数内部如何调用基类构造函数

转载 作者:行者123 更新时间:2023-11-28 02:46:21 26 4
gpt4 key购买 nike

#include <iostream>
#include <string>
using namespace std;

class A
{
private:
int ai;
string as;
};
class B : public A
{
private:
int bi;
string bs;
};


int main()
{
B bob;

return 0;
}

A 类和 B 类有默认构造函数。而且我知道将首先调用 A 类默认构造函数,然后调用 B 类默认构造函数。但问题是这在内部是如何发生的?数据成员是否按继承顺序构造?编译器如何/在何处从 dervied ctor 调用 base ctor?

最佳答案

基本上是先初始化基类,然后按声明顺序初始化数据成员。一个异常(exception)是虚拟基类,它们首先从最派生类初始化。另一个异常(exception)是委派构造函数。


Standardeese:在 C++11 中,这是由 §12.6.2/10 指定的:

In a non-delegating constructor, initialization proceeds in the following order:

  • First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized inthe order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes,where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.
  • Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list(regardless of the order of the mem-initializers).
  • Then, non-static data members are initialized in the order they were declared in the class definition(again regardless of the order of the mem-initializers).
  • Finally, the compound-statement of the constructor body is executed.

[Note: The declaration order is mandated to ensure that base and member subobjects are destroyed in thereverse order of initialization. —end note ]


至于这在内部是如何工作的,一种常见的技术是构造函数调用其关联的基类构造函数和普通成员构造函数。如果您忽略虚基和构造函数委托(delegate),并考虑类 T 的实例化,那么当您实例化 T 时,首先发生的是调用 T 构造函数。但这还不是 T 实例本身的初始化。执行仍在该构造函数的内存初始化列表中。在这里它调用各种基础和非基础成员构造函数(递归地发生相同的情况)。最后执行构造函数体。

关于c++ - 派生类构造函数内部如何调用基类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24281500/

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