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.
这篇关于钻石继承最低基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:钻石继承最低基类构造函数


- 从python回调到c++的选项 2022-11-16
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01