![](/img/trans.png)
[英]Inherit from two parent class (which inherit from one base class) but some methods don't work
[英]I'm trying to write a class where the child class will inherit the methods from the parent class, but my code won't compile
我只是想让我的代码编译。 我以前做过这个,它的方法看起来完全一样,但是由于某种原因,当我尝试使用不同的方法运行它时,它不会编译。 错误在 cpp 文件中。 任何帮助都会很棒! 谢谢
错误是:
/tmp/ccexQEF7.o: In function `Animal::Animal(std::string)':
Animal.cpp:(.text+0x11): undefined reference to `vtable for Animal'
collect2: error: ld returned 1 exit status
这是我的 header 文件:
#include <iostream>
#ifndef ANIMAL_H
#define ANIMAL_H
class Animal
{
public:
Animal(std::string name);
std::string get_name();
virtual int get_weight();
virtual int get_age();
protected:
std::string animalName;
};
class Cat: public Animal
{
public:
Cat(double weight, int age);
std::string get_name();
virtual int get_age();
virtual int get_weight();
protected:
std::string catType;
};
#endif
这是我的 cpp 文件:
#include <iostream>
#include "Animal.h"
using namespace std;
Animal::Animal(string name)
{
animalName = name;
};
您必须在基础 class 中明确定义虚拟成员 function get_weight
和get_age
或将它们声明为纯虚函数,例如
class Animal
{
public:
Animal(std::string name);
std::string get_name();
virtual int get_weight() = 0;
virtual int get_age() = 0;
protected:
std::string animalName;
}
在派生类中,您应该使用说明符override
覆盖它们,例如
int get_weight() override;
int get_age() override;
并提供它们的定义。
请注意,最好将成员函数声明为常量函数,例如
class Animal
{
public:
Animal(std::string name);
std::string get_name();
virtual int get_weight() const = 0;
virtual int get_age() const = 0;
protected:
std::string animalName;
}
因为它们似乎不会更改调用它们的对象。
您有两个未定义的虚拟方法:
virtual int get_weight();
virtual int get_age();
必须定义这些方法,以便可以为 class 编译 vtable(虚拟表)。 至少,你需要给他们一个虚拟的实现:
virtual int get_weight() { return 0; }
virtual int get_age() { return 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.