金刚石继承最低基类构造函数 [英] Diamond Inheritance Lowest Base Class Constructor
问题描述
代码如下:
代码:
#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
};
问题:
1.)如果未知类被实例化,我将如何初始化所有的超类?因为只有一个实例将被创建,我如何避免mysef必须调用它的构造函数两次?
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 ?
谢谢
推荐答案
大多数派生类都初始化任何虚拟基类。在你的类层次结构中, Unknown
必须构造虚拟 Animal
基类(例如通过添加 Animal (a)
到其初始化列表。)
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).
当构造一个 Unknown
Fish
或 Bird
都会调用 Animal
构造函数。 未知
将调用 Animal
虚拟基础的构造函数。
When constructing an Unknown
object, neither Fish
nor Bird
will call the Animal
constructor. Unknown
will call the constructor for the Animal
virtual base.
这篇关于金刚石继承最低基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!