gpt4 book ai didi

c++ - 是否跳过了非具体类的虚拟类的基构造函数?

转载 作者:行者123 更新时间:2023-11-28 06:15:05 24 4
gpt4 key购买 nike

我有这个代码:

class Base{
public:
int x;
Base(int x){
this->x = x;
}

virtual ~Base(){
cout<<"base destroyed"<<endl;
}
};

class A: public virtual Base{
public:
A(int x) : Base(x){ //is this base call here skipped?
}

virtual ~A(){
cout<<"a has been destroyed"<<endl;
}
};

class B: public A{
public:
B():Base(10),A(12){ //initialized from here, overwrite attempt
}
};

int main(int argc, char** argv) {
B ey;
cout<<ey.x<<endl;
return 0;
}

我尝试在具体类的构造函数初始化时覆盖它:

B():Base(10),A(12){ 

输出仍然打印 10。

因为 A 类不是我的具体类,它是否跳过了 base 的构造函数?

A(int x):Base(x){

最佳答案

虚基仅由最派生类的构造函数构造,在本例中为 B。 (它们也恰好在构造最派生类的任何非虚直接基之前首先构造。)

因为在你的例子中 A 不是最派生的类,它的构造函数不构造虚拟基。

关于c++ - 是否跳过了非具体类的虚拟类的基构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30473827/

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