![](/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.