未定义的引用,编译错误 [英] undefined reference, compilation error

查看:81
本文介绍了未定义的引用,编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用类继承.我从一本书中获取了一段代码并对其进行了一些调整,以创建类 Mammal 和一个继承 Mammal 成员数据的类 Dog.代码是:

I am trying to use class inheritance. I have taken a code from a book and tweaked it a bit to create Class Mammal and a Class Dog which inherits Mammal member data. The code is:

#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; 
}

当我运行这段代码时,它给了我以下错误:

When I run this code,, it gives me the following error:

C:\cygwin\tmp\cc7m2RsP.o:prog3.cpp:(.text+0x16):对`Dog::Dog()'的未定义引用collect2.exe:错误:ld 返回 1 个退出状态

C:\cygwin\tmp\cc7m2RsP.o:prog3.cpp:(.text+0x16): undefined reference to `Dog::Dog()' collect2.exe: error: ld returned 1 exit status

任何帮助将不胜感激.谢谢.

Any help would be appreciated. Thanks.

推荐答案

你没有定义构造函数,你只是声明了它们:

You didn't define constructors, you only declared them:

class Mammal{
public:
    Mammal();  // <-- declaration

...

class Dog : public Mammal{
public:
    Dog();  // <-- declaration

当您声明构造函数(或任何函数)时,C++ 编译器将在别处查找构造函数的定义.当它找不到它时,它会抱怨.对于基本定义,试试这个:

When you declare a constructor (or any function) then the C++ compiler will look for the constructor's definition elsewhere. And when it can't find it it complains. For basic definitions try this:

class Mammal{
public:
    Mammal() {};  // <-- definition

...

class Dog : public Mammal{
public:
    Dog() {};  // <-- definition

您也可以完全删除它们,因为它们似乎什么都不做(C++ 会为您插入默认构造函数).

You can also remove them entirely since they don't seem to do anything (C++ will insert default constructor for you).

这篇关于未定义的引用,编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆