我正在尝试使用类继承。我从一本书中获取了一段代码并对其进行了一些调整,以创建 Mammal 类和继承 Mammal 成员数据的 Dog 类。代码是:
#include<iostream>
enum BREED{Labrador,Alcetian,Bull,Dalmetian,Pomerarian};
class Mammal{
public:
Mammal();
~Mammal(){}
double getAge(){return age;}
void setAge(int newAge){age=newAge;}
double getWeight(){return weight;}
void setWeight(double newWeight){weight=newWeight;}
void speak(){std::cout<<"Mammal sound!\n";}
protected:
int age;
double weight;
};
class Dog : public Mammal{
public:
Dog();
~Dog(){}
void setBreed(BREED newType){type=newType;}
BREED getBreed(){return type;}
private:
BREED type;
};
int main(){
Dog Figo;
Figo.setAge(2);
Figo.setBreed(Alcetian);
Figo.setWeight(2.5);
std::cout<<"Figo is a "<<Figo.getBreed()<<" dog\n";
std::cout<<"Figo is "<<Figo.getAge()<<" years old\n";
std::cout<<"Figo's weight is "<<Figo.getWeight()<<" kg\n";
Figo.speak();
return 0;
}
当我运行这段代码时,出现以下错误:
C:\cygwin\tmp\cc7m2RsP.o:prog3.cpp:(.text+0x16): 未定义对“Dog::Dog()”的引用 collect2.exe:错误:ld 返回了 1 个退出状态
如有任何帮助,我们将不胜感激。谢谢。
最佳答案
您没有定义构造函数,您只声明了它们:
class Mammal{
public:
Mammal(); // <-- declaration
...
class Dog : public Mammal{
public:
Dog(); // <-- declaration
当您声明构造函数(或任何函数)时,C++ 编译器将在别处查找构造函数的定义。当找不到它时,它会提示。对于基本定义,试试这个:
class Mammal{
public:
Mammal() {}; // <-- definition
...
class Dog : public Mammal{
public:
Dog() {}; // <-- definition
您也可以完全删除它们,因为它们似乎什么都不做(C++ 将为您插入默认构造函数)。
关于c++ - undefined reference ,编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47752165/