【发布时间】: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;放在标头的全局命名空间中。例如,标准库定义了名称count和distance。它们很容易与包含标头的代码中的名称发生冲突。 -
你是如何编译/链接的?
-
“未定义的引用”意味着您没有与目标代码或定义该事物的库链接。如需更详细的帮助,您需要提供您使用的确切构建命令。
-
似乎是配置问题。你如何构建你的可执行文件?