简体   繁体   English

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

[英]Error: no default constructor exists for class

I have a class derived from base class, and set constructors for each classes, but I keep getting error that I do not have any constructor for base class. 我有一个从基类派生的类,并为每个类设置了构造函数,但是我不断收到错误消息,说我没有基类的任何构造函数。

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;
    }
}

Here I get an error on Huey() and it says " no default constructor exists for 'Dog'". 在这里,我在Huey()上收到一个错误,它说“'Dog'不存在默认构造函数”。 But I think I have created a constructor for class Dog. 但是我想我已经为Dog类创建了一个构造函数。 Can you please explain why this code is wrong? 您能解释一下为什么此代码错误吗?

When you specify any constructor of your own, the default constructor is not created anymore. 当您指定自己的任何构造函数时,将不再创建默认构造函数。 However, you can just add it back. 但是,您可以将其重新添加。

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;
    }
};

EDIT: It seems like you want to call your custom Dog constructor from Huey . 编辑:似乎您想从Huey调用自定义的Dog构造函数。 It is done like so 像这样完成

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;
    }
};

You need to create a constructor with no parameters and no implementation. 您需要创建一个没有参数也没有实现的构造函数。 As below: 如下:

 public:
    Dog() = default;

Two ways: 1) have a default constructor with no params. 两种方法:1)使用没有参数的默认构造函数。 2) call the existing constructor you have in Dog from Huey ( this is the right thing in your case since Huey is a Dog after all). 2)从Huey调用Dog中现有的构造函数(这对您来说是正确的,因为Huey毕竟是Dog)。 Huey is currently calling the default constructor of Dog since this isn't defined and explicitly called. Huey当前正在调用Dog的默认构造函数,因为尚未定义和显式调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM