gpt4 book ai didi

c++ - 具有组合的构造函数调用顺序

转载 作者:搜寻专家 更新时间:2023-10-31 01:09:36 26 4
gpt4 key购买 nike

我有一个 A 类和 B 类。 C 类派生自 B 类,并具有 A 类对象作为组合。 http://ideone.com/JGT48M

#include "iostream"
using namespace std;

class A {
int i;
public:
A(int ii) : i(ii) {
cout << "\n Constructor of A is called \n";

}
~A() {
cout << "\n destructor of A is called \n";
}
void f() const {}
};

class B {
int i;
public:
B(int ii) : i(ii) {
cout << "\n Constructor of B is called \n";
}
~B() {
cout << "\n destructor of B is called \n";
}
void f() const {}
};

class C : public B {
A a;
public:
C(int ii) : a(ii), B(ii) {
cout << "\n Constructor of C is called \n";
}
~C() {
cout << "\n destructor of C is called \n";
} // Calls ~A() and ~B()
void f() const { // Redefinition
a.f();
B::f();
}
};

int main() {
C c(47);
} ///:~

我读到构造函数的调用基于它们在派生类构造函数中的调用方式。我的意思是让有一个名为 REF 的类从 REF_BASE1 和 REF_BASE2 派生

 REF (int ii) : REF_BASE2(ii), REF_BASE1 (ii) {

表示首先调用 REF_BASE2,然后调用 REF_BASE1,然后调用 REF 构造函数。如果我们像这样定义它

REF (int ii) : REF_BASE1(ii), REF_BASE2 (ii) {

意味着首先调用 REF_BASE1,然后调用 REF_BASE2,然后调用 REF 构造函数。

然而,在我上面的程序中,我已经明确地“错误地”指出,内部组合变量 A 首先被初始化,然后 B 应该被初始化,但是编译器以正确的方式做到了,但没有让我知道我的错误

无论我在派生类构造函数初始化列表中指定的顺序如何,上述程序的输出都是

Constructor of B is called 

Constructor of A is called

Constructor of C is called

destructor of C is called

destructor of A is called

destructor of B is called

我的问题是1)为什么编译器不提示?还是我是对的?2) 派生构造函数中的顺序是否没有严格遵守?

最佳答案

我将从第二个问题开始:

2) is the order in derived constructor not followed strictly ?

顺序不是出现在构造函数的初始化列表中的顺序,而是基类出现在类定义中的顺序。

所以如果你的类定义是这样的:

struct A : B, C
{
// ...
};

然后 B 的构造函数将在 C 的构造函数之前被调用,无论您在 A 的初始化列表中指定什么顺序的构造函数。

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 in the 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.

现在第一个问题:

1) why does compiler not complain ?

编译器可能警告您构造函数初始化列表中的初始化顺序与基类列表中的不同(GCC 使用-Wall),但是不必。最终,只有后者才是重要的。

关于c++ - 具有组合的构造函数调用顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16873215/

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