为什么我总是收到错误:"未定义对'robots::robots()'的引用

Why do I keep getting the error: "undefined reference to 'robots::robots()'

本文关键字:robots 引用 未定义 错误 为什么      更新时间:2023-10-16

我正在创建一个程序来练习我在类和文件上的知识,但我可以让它工作。以前我收到一个错误,说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();
}

有人可以发现为什么我不断收到此错误。

你只是在编译你的主文件.cpp这就是为什么编译器无法链接你的函数定义。用

g++ main.cpp enemy_definitions.cpp

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