c++派生类错误
C++ Derived Class Error
我正在努力适应上课。这里我创建了一个基类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
成员将不会初始化并且具有未定义的值。
相关文章:
- 使用 std::enable_if 限制派生类的模板参数时出现编译错误
- C++如果采用类类型的函数被传递派生类型,有没有办法给出错误?
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 返回派生类型时出现协变类型错误
- 错误:基类在从基类父派生类 Son 时未定义
- 通过基类引用派生类后打印的错误值
- 尝试删除指向派生对象的基指针时断言错误
- C++ 将派生类的成员函数指针作为参数传递时选择了错误的模板专用化
- 由于从 std::map 派生的类中的 std::map 迭代器导致的内存错误
- 如何修复派生类给出错误'declaration has no storage class or type specifier'?
- 简单派生类上的Linux GCC链接错误
- 通过参考将派生的类传递给运算符会产生错误
- 使用从WINRT网格类派生的抽象类时,Casttobase未解决的外部符号错误
- 尝试通过基类指针访问派生的类成员函数将导致什么样的错误
- 在派生类CTOR中接收基类副本是错误的吗?
- 在向量中使用派生的可移动但不可压缩的会导致编译错误
- 为什么当我有两个函数时编译器没有显示错误,一个将采用基类,一个将派生类作为参数
- 错误C2509:成员函数未在派生类中声明
- std::unique_ptr 编译器错误:派生类的成员无法访问基类的私有成员
- C++模板参数失败,不是从错误派生的