定义静态类字段时多个已定义符号的链接器错误

Linker errors for multiple defined symbols when defining a static class field

本文关键字:定义 符号 链接 错误 定义符 静态类 字段      更新时间:2023-10-16

我有一个类,我在其中定义了一个静态整数,我希望它能跟踪该类中有多少对象被实例化。

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中。