c++派生类错误

C++ Derived Class Error

本文关键字:错误 派生 c++      更新时间:2023-10-16

我正在努力适应上课。这里我创建了一个基类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
};

编辑:

在删除Animal()后,我得到一个错误,说'Animal':没有合适的默认构造函数可用

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