C++对类的未定义引用(1 个标头 2 cpp)
C++ undefined reference to class (1 header 2 cpp's)
我正在读一本书(傻瓜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
- OSX clang++:用于 cpp 文件中显式实例化模板的体系结构x86_64的未定义符号
- CPP 程序中未定义的行为
- .cpp文件中未定义的引用错误
- 安卓工作室 |CPP 文件错误错误: 位图库中对"AndroidBitmap_unlockPixels"的未定义引用
- 体系结构x86_64的未定义符号:c++/ h 文件和 cpp 文件
- MySQL 连接器 CPP 在 CentOS 6 中未定义的引用
- C++对类的未定义引用(1 个标头 2 cpp)
- 从用户定义的头文件调用函数时出现未定义的引用错误,其实现位于.cpp文件中
- Rcpp - 来源Cpp - 未定义的符号
- 看起来如此主要的错误.cpp:(.text.startup+0xd6):未定义对"vtable for Counter"的引用?
- Cpp 未定义引用 'Apache:: thrift:: transport:: TSocket:: TSocket (std:: string const&, int)'
- main.cpp:(.text+0x8ea):在C++中未定义的引用
- 在 cpp 正文中声明方法时未定义的符号
- Android Studio TensorFlow CPP Build - 未定义引用
- 对于我的 ComplexNumber 中的某些方法,我得到了一个奇怪的未定义错误引用.cpp,不过我对模板很陌生
- 对Google :: Protobuf的未定义引用在ROS CPP中
- yaml-cpp:创建一个未定义的节点
- main.cpp:(.text+0x8f):对[对象方法]的未定义引用
- 谷歌语音识别(cpp示例):对AssignDescriptors()的未定义引用
- cpp 未定义对"class::method"的引用