菱形多重继承图案
diamond shaped multiple inheritance pattern
本文关键字:多重继承 更新时间:2023-10-16
下面是多重继承中面临的钻石问题,
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 ! ");
}
我得到的输出是
- 空基构造函数
- 派生2一个arg构造函数
- 派生1一个arg构造函数
- 派生构造函数
- 空派生析构函数
- 空的Derived2析构函数
- 空的Derived1析构函数
- 空基析构函数
我想知道为什么我的derObj参数,即"如果可以的话打印这个"没有打印出来,并且输出不像
- 空基构造函数
- 派生2一个arg构造函数
- 如果可以的话,打印一下
- 派生1一个arg构造函数
- 派生构造函数
- 空派生析构函数
- 空的Derived2析构函数
- 空的Derived1析构函数
- 空基析构函数
这与虚拟继承有关。
当一个类以虚拟方式继承时,层次结构中最派生的类有责任调用其构造函数:此处为Derived
。
由于Base
是默认可构造的,并且您没有精确计算任何内容,因此Derived
调用Base
的默认构造函数。
如果要打印字符串,请使用:
Derived(const string & strVar) : Base(strVar), Derived1(strVar), Derived2(strVar)
{
std::cout << "Derived Constructorn";
}
您可以删除默认构造函数,让编译器诊断问题,尽管并非所有编译器都会给出非常有用的消息。
相关文章:
- 关于C++中具有多重继承"this"指针的说明
- C++中模板化异常类的多重继承
- 虚拟继承中是否存在多重继承?
- 如何在 c++ 多重继承中调用父非虚函数?
- 多重继承相同的方法名,没有歧义
- 使用enable_if解决多重继承歧义
- 多重继承导致虚假的模糊虚拟函数过载
- 多重继承和访问不明确的元素
- C++ 多重继承:使用基类 A 的实现实现基类 B 的抽象方法
- 多重继承中的派生类的行为类似于聚合
- 为什么我的 Hippomock 期望在使用多重继承时失败
- 带有此指针的模板类多重继承构造函数不起作用?
- 使用多重继承时出现编译错误
- 增强多重继承的序列化
- 多重继承:跳过'virtual'关键字并拒绝菱形层次结构的使用?
- 仅函数的多重继承 - 没有虚拟和 CRTP
- C++多重继承和鸭子类型
- C++两次从文件保存对象读取多重继承
- 从多重继承中的派生类函数调用适当的父类函数
- C++具有多重继承的构造函数重载解析