以下是多重继承所面临的钻石难题,
class Base {
public:
Base() {
cout << "Empty Base constructor " << endl;
}
Base(const string & strVar) {
m_strVar = strVar;
cout << m_strVar << endl;
}
virtual ~Base() {
cout << "Empty Base destructor " << endl;
}
virtual const string & strVar() const {
return m_strVar;
}
string m_strVar;
};
class Derived1: public virtual Base {
public:
Derived1() {
cout << "Empty Derived1 constructor " << endl;
}
Derived1(const string & strVar) : Base(strVar) {
cout << " Derived1 one arg constructor" << endl;
}
~Derived1() {
cout << "Empty Derived1 destructor " << endl;
}
};
class Derived2: public virtual Base {
public:
Derived2() {
cout << "Empty Derived2 constructor " << endl;
}
Derived2(const string & strVar) : Base(strVar) {
cout << "Derived2 one arg constructor" << endl;
}
~Derived2() {
cout << "Empty Derived2 destructor " << endl;
}
};
class Derived: public Derived1, public Derived2 {
public:
Derived(const string & strVar) : Derived1(strVar), Derived2(strVar) {
cout << "Derived Constructor " << endl;
}
~Derived() {
cout << "Empty Derived destructor " << endl;
}
};
int main() {
Derived derObj ("Print this if you can ! ");
}
我得到的输出是
我想知道为什么我的derObj参数(即“如果可以打印此文件”)没有打印并且输出不像
最佳答案
这与虚拟继承有关。
当虚拟继承一个类时,它是层次结构中派生最多的类的责任,即调用其构造函数:此处为Derived
。
由于Base
是默认可构造的,并且您未做任何精确调整,因此Derived
调用Base
的默认构造函数。
如果要打印字符串,请使用:
Derived(const string & strVar) : Base(strVar), Derived1(strVar), Derived2(strVar)
{
std::cout << "Derived Constructor\n";
}
您可以删除默认构造函数,以让编译器诊断问题,尽管并非所有编译器都提供非常有用的消息。