c++ - undefined reference ,编译错误

标签 c++ reference undefined

我正在尝试使用类继承。我从一本书中获取了一段代码并对其进行了一些调整,以创建 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/

相关文章:

javascript - 如何用JS深度检测 "null"或 "undefined"?

c++ - 采用 MiniMax 算法 4x4 的 TicTacToe

c++ - 那么我们可以将虚函数与分配在堆栈上的对象一起使用吗?

ruby-on-rails - $undefined 和 $end 在 Ruby 中指的是什么?

c++ - 使用引用/指针调整数组大小

c++ - 非常量引用返回函数被用作 const 值返回函数的 r 值

javascript - Jquery ID 选择器不适用于变量

c++ - 如何在 C++ 中编写文本编辑器

c++ - GLM 从 vec3 生成旋转矩阵

C++:在不复制/move 太多的情况下解压缩具有引用和值的元组