【发布时间】:2017-12-11 11:41:28
【问题描述】:
我正在尝试使用类继承。我从一本书中获取了一段代码,并对其进行了一些调整,以创建 Class Mammal 和一个继承 Mammal 成员数据的 Class 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 个退出状态
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
这两个类中的大多数方法都只是 DECLARATION,(即没有正文)。必须在某个地方实现(在 C++ 中:定义)
-
你缺少括号 (Dog() { } )
-
Generic wisecrack:如果工具链抱怨 X(这里:“未定义”),X就是通常是它抱怨的原因。 ;-)
Dog::Dog()未定义。 -
忘记定义构造函数真是个愚蠢的错误。谢谢大家的回复。