gpt4 book ai didi

c++ - 多路径继承和

转载 作者:行者123 更新时间:2023-11-28 00:43:05 25 4
gpt4 key购买 nike

在下面的代码中,Multi Path Inheritance 是通过使用 Virtual Class 解决的构造函数是如何工作的?构造函数不能是继承的、虚拟的或静态的。

/*Multi Path Inheritance*/

class A{

public:
int a;
A(){
a=50;
}
};


class B:virtual public A{

public:
/*B(){
a = 40;
}*/

};

class C:virtual public A{

public:
/*C(){
a = 30;
}*/

};

class E:virtual public A{

public:
E(){
a = 40;
}

};

class D : public B, public C, public E{

public:
D(){
cout<<"The value of a is : "<<a<<endl;
}

};

int main(int argc, char *argv[]){

D d;
return 0;
}

最佳答案

基于 12.6.2/10 标准的配额,所以构造函数体将按以下顺序调用:A->B->C->D,所以 a 的最终值为 40。

In a non-delegating constructor, initialization proceeds in thefollowing 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).

关于c++ - 多路径继承和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17804293/

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