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

问题描述 投票:0回答:3

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

[C0中的示例

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

c++ inheritance multiple-inheritance diamond-problem
3个回答
0
投票

而不是打印整数参数,而是尝试打印成员变量的地址。然后尝试使用虚拟继承,它应该可以更好地了解发生了什么。


0
投票

从链接进行绘制具有误导性,它不是菱形,而是更多的Y:


0
投票

尝试调查实例化的TA对象的大小。尺码告诉你什么?对于单人副本,您期望什么尺寸?要两个副本?

© www.soinside.com 2019 - 2024. All rights reserved.