C++对类的未定义引用(1 个标头 2 cpp)

C++ undefined reference to class (1 header 2 cpp's)

本文关键字:cpp 未定义 引用 C++      更新时间:2023-10-16

我正在读一本书(傻瓜C++(以及观看YouTube视频以学习如何编码。 我目前正在为非常简单的类函数而苦苦挣扎。

主.cpp

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include "Test.h"
using namespace std;
int x;
int main(int nNumberofArgs, char* pszArgs[])
{
combat fight;
cout << x;
fight.dodmg();
cout << x;
return 0;
}

Test.h我的头文件与类

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
using namespace std;
#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED
class combat
{
public:
int dodmg();
void zero_out();
private:
int x;
};

#endif // TEST_H_INCLUDED

测试.cpp类函数

#include "Test.h"

int combat::dodmg()
{
x = x - 5;
return x;
}
void combat::zero_out()
{
x = 20
}

我试图使这变得非常简单,只是为了弄清楚如何上课。 我包含了很多 #includes 只是为了确保它不是像我需要字符串那样愚蠢的东西。

我不确定为什么,但我观看的视频只是标题说 ifndef TEST_H(在他们各自的代码中,我的代码也有_INCLUDE,我尝试删除它,但它仍然不起作用。

我不幸的错误

在主.cpp的第 14 行 fight.dodmg((; 它说

Beginning_Programming-CPPPlaying_with_classmain.cpp|14|undefined reference to `combat::dodmg()'|

然后低于此

||error: ld returned 1 exit status|

你是如何编译的?我认为这是一个问题,因为您没有编译 Test.cpp 文件。如果尚未编译,请尝试使用以下命令进行编译:

g++ main.cpp Test.cpp -o MyProgram

更新:

很少的事情,你在 Text.h 中没有 #ifndef 指令的结束语句,你需要一个构造函数来设置 x 的值,所以我在战斗类中添加了一个,而且你在 zero_out 函数中缺少一个分号。我在我更改的所有行中添加了注释。

好的试试这个:

测试.h

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
using namespace std;
#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED
class combat
{
public:
combat(); // added constructor
int dodmg();
void zero_out();
private:
int x;
};
#endif // closed #ifndef

文本.cpp

#include "Test.h"
combat::combat() // implemented constructor
{
x = 20;
}
int combat::dodmg()
{
x = x - 5;
return x;
}
void combat::zero_out()
{
x = 20; // added ';'
}

希望这有帮助,

最终编辑:我认为在这种情况下您真的不需要标题保护,您可以删除"#ifndef、#define 和 #endif"行,而看不到真正的区别

听起来你为编译器提供了错误的参数。您的头文件 (Test.h( 仅提供方法的签名,但实现在源文件 (Test.cpp( 中给出。

这是编写C++(或 C(代码的重要组成部分。您的编译器不会自动搜索源文件,因此您需要告诉它在哪里查找,例如:

g++ -std=c++11 main.cpp Test.cpp -o main