【发布时间】:2020-12-10 07:09:41
【问题描述】:
我正在尝试通过使用继承来实现从父类派生的子类,但我不断收到此错误:
/tmp/ccThP1Yc.o: In function `Cat::Cat(double, int)':
Animal.cpp:(.text+0x11a): undefined reference to `vtable for Cat'
collect2: error: ld returned 1 exit status
我正在使用 Cat::Cat(double weight, int age):Animal(name) 行的继承 'name' 是 Animal 的构造函数,我想将它重新用于 Cat,也将 Animal 中的其他方法用于 Cat。
这是我的头文件:
#include <iostream>
#include <string>
#ifndef ANIMAL_H
#define ANIMAL_H
class Animal
{
public:
Animal(std::string name);
std::string get_name();
virtual double get_weight();
virtual int get_age();
protected:
std::string animalName;
};
class Cat: public Animal
{
public:
Cat(double weight, int age);
std::string get_name();
int get_age();
double get_weight();
protected:
std::string catType; //type of cat (i.e. Tabby, Siamese)
};
#endif
这是我的 cpp 文件:
#include <iostream>
#include <string>
#include "Animal.h"
using namespace std;
Animal::Animal(string name)
{
animalName = name;
};
string Animal::get_name()
{
return animalName;
};
double Animal::get_weight()
{
return 0.0;
};
int Animal::get_age()
{
return 0;
}
Cat::Cat(double weight, int age):Animal("Cat") ////error is here
{
};
如果有任何帮助,我将不胜感激!谢谢!
【问题讨论】:
-
完全不相关:在标题中,将包含放在 include guard 内
-
也完全不相关:函数不需要
;s