类的 Ctor-初始值设定项不调用相应的构造函数

Ctor-initializer for a class doesn't call to the appropriate constructor

本文关键字:调用 构造函数 Ctor- 类的      更新时间:2023-10-16

我正在玩构造/解构对象。以下是我尝试过的http://coliru.stacked-crooked.com/a/ff17cc5649897430:

#include <iostream>
struct B{
    B(){ std::cout << "B()" << std::endl; }
    B(int){ std::cout << "B(int)" << std::endl; }
};
struct A : virtual B
{
    int B;
    A(int a) : B(a) { std::cout << "A(int)" << std::endl; }
} a(10);
int main()
{
}

程序输出为

B()
A(int)

为什么?我在元素初始化器中显式指定要调用的类B的构造函数。

B(a)正在构造B成员变量。给变量起个好名字,你就会看到你想看到的东西。