Diamond Inheritance Lowest Base Class Constructor(钻石继承最低基类构造函数)
问题描述
代码如下:
代码:
#include 使用命名空间标准;类动物{一个;上市:动物(int a) : a(a){}int geta(){返回一个;}};类鸟:虚拟公共动物{字符串 b;上市:Bird(int a, string b) : Animal(a), b(b){}};类鱼:虚拟公共动物{国际f;上市:Fish(int a , int f) : Animal(a) , f(f){}};未知类:公共鸟,公共鱼{字符你;上市:未知(int a,int f,string b,char u): Bird(a , b) , Fish(a , f) , u(u){}//问题};
问题:
1.)如果实例化了 Unknown 类,我将如何初始化所有超类?由于只会创建一个 Animal 实例,如何避免 mysef 不得不两次调用其构造函数?
谢谢
最派生的类初始化任何虚拟基类.在您的类层次结构中,Unknown
必须构造虚拟的 Animal
基类(例如,通过将 Animal(a)
添加到其初始化列表中).>
在构造Unknown
对象时,Fish
和Bird
都不会调用Animal
构造函数.Unknown
将调用 Animal
虚拟基础的构造函数.
The Code is as follow :
The Code :
#include <iostream>
using namespace std;
class Animal{
int a;
public:
Animal(int a) : a(a){}
int geta(){return a;}
};
class Bird : virtual public Animal{
string b;
public:
Bird(int a , string b) : Animal(a) , b(b){}
};
class Fish : virtual public Animal{
int f;
public:
Fish(int a , int f) : Animal(a) , f(f){}
};
class Unknown : public Bird, public Fish{
char u;
public:
Unknown(int a , int f , string b , char u )
: Bird(a , b) , Fish(a , f) , u(u){} //Problem
};
The Question :
1.)How am I going to initialize all the superclass if the Unknown class is instantiated?Since there's only one instance of Animal will be created , how can I avoid mysef from having to call its constructor twice ?
Thank you
The most derived class initializes any virtual base classes. In your class hierarchy, Unknown
must construct the virtual Animal
base class (e.g. by adding Animal(a)
to its initialization list).
When constructing an Unknown
object, neither Fish
nor Bird
will call the Animal
constructor. Unknown
will call the constructor for the Animal
virtual base.
这篇关于钻石继承最低基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:钻石继承最低基类构造函数


基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09