C++ 派生类错误

标签 c++ class constructor

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

相关文章:

c++ - 调试类函数实现 C++

java - 如何使 JavaCompiler.CompilationTask 使用自定义 ClassLoader 或将 .class 文件用于 missin .java 文件?

C++构造函数继承(从派生类调用构造函数)

javascript - 如何将新属性及其参数添加到现有原型(prototype)/构造函数

design-patterns - 如何使构造函数返回子类对象

c++ - 在 C++ 中将信息打印到屏幕的解决方案?

c++ - 私有(private)内部成员的运算符重载

c++ - 从文件输入和输出

php - 初始化一个可能用不到的类

c++ - 关于 throw 物体的问题