c++ - 我正在尝试编写一个类,其中子类将从父类继承方法,但我的代码无法编译
问题描述
我只是想让我的代码编译。我以前做过这个,它的方法看起来完全一样,但是由于某种原因,当我尝试使用不同的方法运行它时,它不会编译。错误在 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;
}
因为它们似乎不会更改调用它们的对象。
推荐阅读
- html - 如何将我的 html 集成到typo3 CMS?
- java - 在java中过滤一个RDD以分成2个新的RDD
- r - plyr::mapvalues 的 dplyr 替代品(使用字典重新编码)
- charts - 如何使用 Office Js 插入瀑布图?
- python - 我有一个字典,其中所有元素都是字节。我怎样才能得到一个字符串的字典?
- anaconda - 将 Anaconda 指向源文件的多个位置
- c++ - int **a 和 int a[][] 作为 C 和 C++ 中的函数参数之间的确切区别是什么?
- ontology - 您如何评估由一个类和数百个人组成的大规模本体(CSO)?
- design-patterns - 使用工厂设计模式如何阻止一个类必须预测它必须创建的对象类
- windows-server - 关闭 RDP 后如何防止注销/丢失屏幕