我试图习惯上课。在这里,我创建了一个名为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;
}
答案 0 :(得分:1)
未定义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()后,我收到一条错误消息“动物”:没有合适的默认构造函数
您需要实现默认构造函数(参见上文)。没有它,int
成员将不会被初始化并具有未定义的值。