钻石继承最低基类构造函数

2021-12-30 00:00:00 diamond-problem constructor c++

代码如下:

代码:

#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 对象时,FishBird 都不会调用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.

相关文章