问题描述
我只是想让我的代码进行编译。我之前已经做过,它的方法看起来完全一样,但是由于某些原因,当我尝试使用不同的方法运行它时,它不会编译。错误在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
这是我的头文件:
#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;
};
解决方法
您必须在基类中明确定义虚拟成员函数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();
必须定义这些方法,以便可以为类编译vtable(虚拟表)。至少,您需要给他们一个虚拟的实现:
virtual int get_weight() { return 0; }
virtual int get_age() { return 0; }