我正在学习多重继承和菱形问题,但是对于为什么可以在没有编译器错误的情况下调用基类构造函数两次却感到困惑。
来自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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句