为什么派生类可以调用基类构造函数两次?

帅哥

我正在学习多重继承和菱形问题,但是对于为什么可以在没有编译器错误的情况下调用基类构造函数两次却感到困惑。

来自https://www.geeksforgeeks.org/multiple-inheritance-in-c/的示例

#include<iostream> 
using namespace std; 

class Person { 
   // Data members of person  
public: 
    Person(int x)  { cout << "Person::Person(int ) called" << endl;   } 
    int y;                                                               \\ <- I added this
}; 

class Faculty : public Person { 
   // data members of Faculty 
public: 
    Faculty(int x):Person(x)   { 
       cout<<"Faculty::Faculty(int ) called"<< endl; 
    } 
}; 

class Student : public Person { 
   // data members of Student 
public: 
    Student(int x):Person(x) { 
        cout<<"Student::Student(int ) called"<< endl; 
    } 
}; 

class TA : public Faculty, public Student  { 
public: 
    TA(int x):Student(x), Faculty(x)   { 
        cout<<"TA::TA(int ) called"<< endl; 
    } 
}; 

int main()  { 
    TA ta1(30); 
} 

输出:

Person::Person(int ) called
Faculty::Faculty(int ) called
Person::Person(int ) called
Student::Student(int ) called
TA::TA(int ) called

由于派生类两次TA调用Person构造函数,因此这并不意味着TA将具有相同名称的两个数据成员副本,例如,两个实例int y

贾罗德42

从链接中提取内容具有误导性,它不是菱形,而是更多的Y:

 ----------    ----------
|  Person  |  |  Person  |
 ----------    ----------
      ^             ^
      |             |
 ----------    ----------
|  Student |  |  Faculty |
 ----------    ----------
      ^             ^
      |             |
       \-----   ----/
             \ /
              |
         ----------
        |    TA    |
         ----------

是的,您有PersonStudent::yFaculty::y成员的两个副本

使用虚拟继承,您将拥有仅一个唯一的钻石Person

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么在基类构造函数中看不到派生类属性值?

从Java中的派生类调用基类构造函数

在派生构造函数中的某些代码块之后,在派生类中调用基类构造函数

为什么要调用派生类的析构函数?

C#-在派生类中调用基类和类构造函数

是否可以从基类构造函数调用派生类构造函数?

派生类的构造函数可以比其基类的构造函数具有更多的参数吗?

为什么派生类的构造函数要在C ++中初始化虚拟基类?

为什么派生类需要使用基类构造函数

重写新运算符时,C ++类构造函数被调用两次-为什么

我可以从基类调用派生类构造函数吗?

(为什么)在纯虚拟派生类中是否需要虚拟基类构造函数调用?

为什么为派生类定义副本构造函数要求定义基类的默认构造函数?

让隐式派生类构造函数调用基类构造函数

C ++派生类构造函数调用基类构造函数错误

为什么派生类指针指向基类可以调用派生类成员函数?

C ++为什么基类/结构构造函数不能有多个参数可以从派生隐式调用?

为什么`this`在调用派生类对象时无法从基类方法访问派生类成员

从派生类调用基函数时会发生什么?

从派生类调用构造函数

如何在Scala中从派生类辅助构造函数调用辅助基类构造函数?

从派生类构造函数调用基类构造函数

在声明派生类时调用基类的构造函数

从模板派生类调用模板基类的构造函数

在派生类构造函数中引发异常。为什么调用基类析构函数而不是派生类析构函数?

友元函数是继承的吗?为什么基类 FRIEND 函数可以在派生类对象上工作?

在派生类 C++ 的构造函数中调用基类的构造函数

如何使用指向函数的指针在基类构造函数中调用派生类的方法?

为什么派生类的私有虚拟成员函数可以从基类访问