我正在学习多重继承和菱形问题,但我很困惑为什么基类构造函数可以被调用两次而没有编译器错误。
来自 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::y
和 Faculty::y
)。通过虚拟继承,您拥有一颗只有一个唯一的钻石
Person
.
关于c++ - 为什么派生类可以调用基类构造函数两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59331217/