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

标签 c++ inheritance multiple-inheritance diamond-problem

我正在学习多重继承和菱形问题,但我很困惑为什么基类构造函数可以被调用两次而没有编译器错误。

来自 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 的两个实例?

最佳答案

从链接中绘制具有误导性,它不是菱形,而是 Y:

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

是的,您有两个 Person 成员的拷贝( Student::yFaculty::y )。

通过虚拟继承,您拥有一颗只有一个唯一的钻石 Person .

关于c++ - 为什么派生类可以调用基类构造函数两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59331217/

相关文章:

c++ - 随机数生成器未在设置的变量参数内生成

angular - super() 中的 typescript 依赖注入(inject)

c++ - 构造函数内部 "this"的 dynamic_cast

C# 多接口(interface)继承不允许具有相同名称的公共(public)访问修饰符

c++ 公共(public)继承的类成员不能用作默认参数

c++ - Visual Studio - 升级后为 "Unknown Compiler version"

c++ - 同步访问分配的内存

c# - 如何覆盖非虚方法?

Java:实例化还是继承?

java - JDK 8 中的默认值是 Java 中多重继承的一种形式吗?