【问题标题】:Why do I keep getting the error: "undefined reference to 'robots::robots()'为什么我不断收到错误消息:“未定义对 'robots::robots()' 的引用
【发布时间】:2018-12-13 18:11:17
【问题描述】:

我正在创建一个程序来练习我对类和文件的了解,但我可以让它发挥作用。以前我收到一个错误,说 robots::robots() 被定义了多次,但现在我有这个错误,说未定义对“robots::robots()”的引用。这是enemy_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;
};

这里是enemy_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();
}

有人能找出我为什么不断收到此错误吗?

【问题讨论】:

  • 永远不要将using namespace std; 放在标头的全局命名空间中。例如,标准库定义了名称countdistance。它们很容易与包含标头的代码中的名称发生冲突。
  • 你是如何编译/链接的?
  • “未定义的引用”意味着您没有与目标代码或定义该事物的库链接。如需更详细的帮助,您需要提供您使用的确切构建命令。
  • 似乎是配置问题。你如何构建你的可执行文件?

标签: c++ file class include


【解决方案1】:

您只是在编译您的 main.cpp 文件,这就是编译器无法链接您的函数定义的原因。使用

g++ main.cpp enemy_definitions.cpp

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

【讨论】:

  • 但是从我正在阅读的书中我不需要使用 g++ 并且制作这本书的人设法链接文件而不必使用 g++ 那么我怎么能不使用 g++ 来做到这一点
  • 那本书怎么告诉你编译呢?
  • 好吧,他说要为您当前的项目创建一个空的源文件,然后选择调试和发布,它应该可以工作
  • 您的 IDE 必须在您构建时显示它正在使用的构建命令。您可以检查它是否编译了这两个文件。
猜你喜欢
  • 2014-04-12
  • 2016-11-02
  • 1970-01-01
  • 1970-01-01
  • 2014-03-31
  • 1970-01-01
  • 2020-01-17
  • 2019-09-10
  • 2011-08-07
相关资源
最近更新 更多