gpt4 book ai didi

C++ 派生类错误

转载 作者:行者123 更新时间:2023-11-28 06:00:47 25 4
gpt4 key购买 nike

我正在努力适应类。在这里,我创建了一个名为 Animal 的基类和一个名为 Dog 的派生类。

我最初能够让基类单独工作,但是当我尝试添加派生类时,事情变得一团糟并且出现错误。这是代码,如果您能让我知道我做错了什么,那就太好了!

#include <iostream>
#include <string>
using namespace std;

class Animal{
protected:

int height, weight;
string name;

public:

int getHeight() { return height; };
int getWeight() { return weight; };
string getName() { return name; };

Animal();
Animal(int height, int weight, string name);
};

Animal::Animal(int height, int weight, string name){
this->height = height;
this->weight = weight;
this->name = name;
}


class Dog : public Animal{
private:

string sound;

public:

string getSound() { return sound; };
Dog(int height, string sound);
};

Dog::Dog(int height, string sound){
this->height = height;
this->sound = sound;
}

int main()
{
Animal jeff(12, 50, "Jeff");
cout << "Height:\t" << jeff.getHeight << endl;
cout << "Weight:\t" << jeff.getWeight << endl;
cout << "Name:\t" << jeff.getName << endl << endl;

Dog chip(10, "Woof");
cout << "Height:\t" << chip.getHeight() << endl;
cout << "Sound:\t" << chip.getSound() << endl;
}

最佳答案

未定义 Animal 类的默认构造函数。你需要:

Animal::Animal() : height(0), weight(0) // Or any other desired default values
{
}

您还应该在基类上有一个虚拟析构函数。

class Animal
{
public:
~Animal() {} // Required for `Animal* a = new Dog(...); delete a;`
// deletion via base pointer to work correctly
};

编辑:

Upon removal of Animal() I get an error that says 'Animal': no appropriate default constructor available

您需要实现默认构造函数(见上文)。没有它,int 成员将不会被初始化并且具有未定义的值。

关于C++ 派生类错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33326320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com