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.
这篇关于钻石继承最低基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:钻石继承最低基类构造函数
基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
