【发布时间】:2012-09-23 06:24:42
【问题描述】:
#include<iostream>
using namespace std;
class Person {
// Data members of person
public:
Person(int x) { cout << "Person::Person(int ) called" << endl; }
};
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);
}
O/p:
Person::Person() called
Faculty::Faculty(int ) called
Student::Student(int ) called
TA::TA(int ) called
在上面的菱形中,两个父类是用 virtual 关键字从祖父继承的,因此 Person 类的构造函数只被调用一次。但是为什么祖父母的默认构造函数在这里调用。谁能告诉我确切的原因 非常感谢
【问题讨论】:
-
虚拟继承在哪里?
-
因为越来越多的人要求解决方案;没有帮助,这是我的猜测。
-
除了已经提到的缺少
virtual关键字之外,输出不可能包含“Person::Person() called”,因为您的代码不包含任何可能打印该字符串的代码.确保代码确实符合您的问题。
标签: c++ constructor multiple-inheritance default-constructor