gpt4 book ai didi

c++ - 为什么 C++ 的创建者决定使用构造函数初始化列表来初始化基类?

转载 作者:太空狗 更新时间:2023-10-29 20:35:22 24 4
gpt4 key购买 nike

为什么 C++ 的创建者决定使用构造函数初始化列表来初始化基类?他为什么不选择使用类似于以下代码中第二行注释的语法?

class A{
public:
A() { }
};

class B : A{
public:
B() : A() { } // Why decide to use this one, using constructor initializer, to initialize base class?
B() { A(); } // Why not choose this one? It's easy for me to understand if it was possible.
};

int main(int argc, char *argv[]){
/* do nothing */
}

最佳答案

使用初始化列表的好处是,在构造函数的主体中有一个完全初始化的对象。

class A {
public:
A(const int val) : val(val) { }
private:
const int val;
};

class B : A{
public:
B() : A(123) {
// here A and B are already initialized
}
};

因此您可以保证所有成员,甚至是父级的成员,都不会处于未定义状态。

编辑

在问题的例子中,没有必要调用初始化列表中的基类,这是自动完成的。所以我稍微修改了这个例子。

关于c++ - 为什么 C++ 的创建者决定使用构造函数初始化列表来初始化基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42992573/

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