为什么我不断收到错误消息:“对'robots :: robots()的未定义引用”

时间:2018-07-05 09:53:14

标签: c++ file class include

我正在创建一个程序来练习关于类和文件的知识,但是我可以使它起作用。以前,我收到一个错误消息,说多次定义robots :: robots(),但现在却出现此错误,指出未定义对'robots :: robots()'的引用。这是敌人_definitions.h的代码:

#include <iostream>
using namespace std;

class enemies
{
    public:
    string name;
    int hp;
    int damage;
    virtual void print_information();
};

class robots: public enemies
{
    public:
        robots();
        void print_information();
    private:
        int power_requirement;
};

class zombies: public enemies
{
    public:
        void print_information();
    private:
        int height;
};

class aliens: public enemies
{
    public:
        void print_information();
    private:
        string colour;
};

这是敌人_definitions.cpp的代码:

#include <iostream>
#include "enemy_definitions.h"

void enemies :: print_information()
{
}

robots :: robots()
    {
        cout <<"Name: ";
        cin >> name;
        cout <<"\nhp: ";
        cin >> hp;
        cout <<"\ndamage: ";
        cin >> damage;
        cout <<"\n power_requirement: ";
        cin >> power_requirement;
    }

void robots :: print_information()
{
    cout << this->name << " has ";
    cout << this->hp << "hit-points, ";
    cout << this->damage << " damage and ";
    cout << this->power_requirement << "power requirement";
}

void zombies :: print_information()
{
    cout << this->name << " has ";
    cout << this->hp << "hit-points, ";
    cout << this->damage << " damage and ";
    cout << this->height << "height";
}

void aliens :: print_information()
{
    cout << this->name << " has ";
    cout << this->hp << "hit-points, ";
    cout << this->damage << " damage and ";
    cout << this->colour << "colour";
}

这是main.cpp的代码:

#include <iostream>
#include "enemy_definitions.h"

using namespace std;

int main()
{
robots Bertha;
Bertha.print_information();
}

有人可以找出我为什么继续出现此错误的原因。

1 个答案:

答案 0 :(得分:0)

您仅在编译main.cpp文件,这就是为什么编译器无法链接您的函数定义。使用

g++ main.cpp enemy_definitions.cpp

这应该正确链接您的代码。