gpt4 book ai didi

c++ - 虚拟继承(钻石)——为什么我需要从派生类最多的类向上转换为基类

转载 作者:搜寻专家 更新时间:2023-10-31 00:02:53 25 4
gpt4 key购买 nike

考虑以下几点:

#include <iostream>
#include <string>
using namespace std;


class A {
public:
A(const char* sName) //conversion constructor
: _sName(sName) {cout<<"(1)"<<endl;} ;
A(const A& s) {cout<<"(2)"<<endl;} //copy constructor
virtual ~A() {cout<<"(3)"<<endl;} //destructor
void f1() {cout<<"(4)"<<endl; f2();} //Notice two commands!
virtual void f2() =0;
private:
string _sName;
};



class B1: virtual public A {
public:
B1(const char* sAName, const char* sSName)
: _sName1(sAName), A(sSName) {cout<<"(5)"<<endl;}
B1(const B1& b1) : A(b1) {cout<<"(6)"<<endl;}
~B1() {cout<<"(7)"<<endl;}
virtual void f1() {cout<<"(8)"<<endl;}
virtual void f2() {cout<<"(9)"<<endl; f3();}
virtual void f3() {cout<<"(10)"<<endl;}
private:
string _sName1;
};



class B2: virtual public A {
public:
B2(const char* sAName, const char* sSName)
: _sName2(sAName), A(sSName) {cout<<"(11)"<<endl;}
B2(const B2& b2) : A(b2) {cout<<"(12)"<<endl;}
~B2() {cout<<"(13)"<<endl;}
virtual void f3() {f1(); cout<<"(14)"<<endl;}
private:
string _sName2;
};

class C: public B1, public B2 {
public:
C () : A(" this is A ") , B1(" this is " , " B1 ") , B2 (" this is " , " B2 ") {}
C (const C& c) : A(c) , B1(c) , B2(c) {}
~C() {cout<<"(15)"<<endl;}
virtual void f1() {A::f1(); cout<<"(16)"<<endl;}
void f3 () {cout<<"(17)"<<endl;}
};


int main() {
/* some code */
return 0;
}

如您所见,我在 class C 中添加了 C 的 Ctor(构造函数)的实现。我不清楚的是,如果 B1 在其 Ctor 中为我完成这项工作,为什么我还需要从 C 到 A 的向上转换?意思是,如果我将 C 的 Ctor 写为:

C () : A(" this is A ") , B1(" this is " , " B1 ") , B2 (" this is " , " B2 ") {}

为什么我不能写:

C () : B1(" this is " , " B1 ") , B2 (" this is " , " B2 ") {}

谢谢,罗嫩

最佳答案

虚拟基础的构造函数之前被称为非虚拟分析器。在您的示例中,B1 ctor 无法调用 C 的虚拟基构造函数,因为稍后将调用 B1 ctor 本身。

关于c++ - 虚拟继承(钻石)——为什么我需要从派生类最多的类向上转换为基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7267562/

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