定义静态类字段时多个已定义符号的链接器错误
Linker errors for multiple defined symbols when defining a static class field
我有一个类,我在其中定义了一个静态整数,我希望它能跟踪该类中有多少对象被实例化。
class mob {
public:
mob::mob();
mob::mob(std::string, std::string, int, int, int, int, int);
//some other stuff
private:
//some other stuff
static int mob_count;
};
int mob::mob_count = 0;
然后我定义以下构造函数:
mob::mob(string name, string wName, int lowR, int highR, int health, int defense, int reward)
{
nName = name;
nWeapon.wName = wName;
nWeapon.wRange.Rlow = lowR;
nWeapon.wRange.RHigh = highR;
nHealth = health;
nArmor = defense;
xpReward = reward;
++mob_count;
}
那么我错过了什么?我想我正在做我的教科书告诉我的一切。
我在编译时得到这个
我希望有人能指出我的错误,非常感谢。
编辑:@linuxuser27帮助我解决了我的问题,所以基本上我只是移动了
int mob::mob_count = 0;
从类定义到类实现,如下所示:
暴徒:
class mob {
public:
mob::mob();
mob::mob(std::string, std::string, int, int, int, int, int);
//some other stuff
private:
//some other stuff
static int mob_count;
};
暴徒.cpp
int mob::mob_count = 0;
构造函数保持不变。
我假设你在头文件中声明你的类(例如mob.hpp
),然后将头文件包含在多个编译单元(即文件)中.cpp。基本上是这样的:
主.cpp
#include "mob.hpp"
...
暴徒.cpp
#include "mob.hpp"
...
从头文件中删除int mob::mob_count = 0;
并将其放入mob.cpp
中。
相关文章:
- vscode g++链路故障:体系结构x86_64的未定义符号
- 为函数定义符号不明确的指针参数
- 体系结构x86_64的未定义符号:std:terminate(),typeinfo,运算符delete[],运算符new
- C++ 中 dlsym 的未定义符号
- 仅在 MacOS 上析构函数的未定义符号
- OSX clang++:用于 cpp 文件中显式实例化模板的体系结构x86_64的未定义符号
- PCL 出错:体系结构x86_64 @pcl的未定义符号
- clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用) - 体系结构的未定义符号 x86_64:
- 体系结构x86_64的未定义符号:链接器错误
- C++ std::vector<int> 体系结构的未定义符号 x86_64:
- 生成文件:体系结构x86_64的未定义符号
- libc++abi未定义符号:_ZTVN10__cxxabif120__si-class_type_infoE
- Xcode"体系结构x86_64的未定义符号"
- 体系结构x86_64的未定义符号:找不到原因
- SWIG链接器:未定义符号:_ZN2cv8fastFreeEPv(cv::fastFree(void*))
- 如何修复架构x86_64的未定义符号,Boost Asio 1.58
- 在Qt5上去静态库:架构的未定义符号x86_64:
- 体系结构x86_64的未定义符号:c++/ h 文件和 cpp 文件
- 为什么链接器报告全局函数的乘法定义符号,而不是类静态方法
- 监视 SDK 下的未定义符号"__Unwind_SjLj_Unregister"