我正在努力适应类。在这里,我创建了一个名为 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/