C++ 多级继承 - 调用基本构造函数错误

C++ multilevel inheritance - Calling Base Constructor Error

所以我有一个相当复杂的程序,我现在不想进入。我将包括一个相同过程的玩具示例,然后更详细地介绍它。

在我的程序中,我遇到了多级继承错误 constructor for 'Hunter' must explicitly initialize the base class 'WorldObject' which does not have a default constructorWorldObject -> Creature -> Hunter.

为了重新创建相同的结构,我做了以下操作:

class Base
{
protected:
    int a;
public:
    Base(int a): a(a) { print("Base contructed"); }
    ~Base() { print("Base destroyed"); }
    virtual void printData() = 0;
};



class Derived1 : public Base
{
protected:
    int b;
public:
    Derived1(int a, int b): b(b), Base(a) { print("Derived1 contructed"); }
    ~Derived1() { print("Derived1 destroyed"); }
};


class Derived2 : public Derived1
{
protected:
    int c;
public:
    Derived2(int a, int b, int c) : c(c), Derived1(a, b) { print("Derived2 contructed"); }
    ~Derived2() { print("Derived2 destroyed"); }
    virtual void printData(){ //... }
}; 

在这里,Derived2 class 的构造函数通过初始化列表创建了 Derived1,而这又构造了 Base "indirectly"。这像我预期的那样工作。

然而,在我的复杂代码中,Hunter class 需要显式调用 WorldObject 构造函数。这看起来像:

Hunter(sf::Texture &texture, float x, float y, sf::Font& font) : 
        WorldObject(texture,x, y, font),
        Creature(texture, x, y, font)
    { //... }

在这里,Creature 构造函数只是将每个参数传递给 WorldObject 构造函数。 WorldObject 只有这个构造函数:

WorldObject(sf::Texture& texture, float x, float y, sf::Font& font) : m_sprite(texture)
{ //... }

使用的 Creature 构造函数如下所示:

    Creature(sf::Texture &texture, float x, float y, sf::Font& font) : 
    WorldObject(texture, x, y, font), 
    NN(n_input_units, n_hidden_units, n_output_units)
{ //... }

为什么我需要在我的程序中直接初始化 WorldObject 和 Creature,但在玩具示例中它可以在没有显式 Base 构造函数的情况下工作?

((预编译器也报错说WorldObject没有默认构造函数,编译时出现上述错误))

我猜想在您的 复杂 代码中,Hunter 直接继承自 WorldObject 而不是通过 Creature 间接继承。如果 Creature 继承 WorldObject 永远不会 Hunter 需要将任何参数传递给 WorldObject