错误:类不存在默认构造函数

Error: no default constructor exists for class

本文关键字:默认 构造函数 不存在 错误      更新时间:2023-10-16

我有一个从基类派生的类,并为每个类设置构造函数,但我不断收到错误,因为我没有任何基类的构造函数。

class Dog
    {
    protected:
    string name;
    int age;
    public:
    Dog(string dogsName, int dogsAge)
    {
        name = dogsName;
        age = dogsAge;
    }
    virtual void Bark()
    {
        cout << "Woof Woof I am a dog" << endl;
    }

class Huey: public Dog
{
public:
    Huey()
    {
        name = "goodboy";
        age = 13;
    }
     void Bark()
    {
    cout << "woof" << endl;
    }
}

在这里,我在 Huey() 上收到一个错误,它说"'狗'不存在默认构造函数"。但我想我已经为 Dog 类创建了一个构造函数。你能解释一下为什么这段代码是错误的吗?

指定自己的任何构造函数时,将不再创建默认构造函数。但是,您可以将其添加回来。

class Dog
    {
    protected:
    string name;
    int age;
    public:
    Dog() = default;
    Dog(string dogsName, int dogsAge)
    {
        name = dogsName;
        age = dogsAge;
    }
    virtual void Bark()
    {
        cout << "Woof Woof I am a dog" << endl;
    }
};
class Huey: public Dog
{
public:
    Huey()
    {
        name = "goodboy";
        age = 13;
    }
     void Bark()
    {
    cout << "woof" << endl;
    }
};

编辑:似乎您想从Huey调用自定义Dog构造函数。它是这样完成

class Dog
    {
    protected:
    string name;
    int age;
    public:
    Dog(string dogsName, int dogsAge)
    {
        name = dogsName;
        age = dogsAge;
    }
    virtual void Bark()
    {
        cout << "Woof Woof I am a dog" << endl;
    }
};
class Huey: public Dog
{
public:
    Huey() : Dog("goodboy", 13) {}
    void Bark()
    {
    cout << "woof" << endl;
    }
};

您需要创建一个没有参数和实现的构造函数。如下:

 public:
    Dog() = default;

两种方式:1) 有一个没有参数的默认构造函数。2) 从休伊调用您在 Dog 中的现有构造函数(这在您的情况下是正确的,因为休伊毕竟是一只狗)。Huey 目前正在调用 Dog 的默认构造函数,因为它没有定义和显式调用。