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

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

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

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;
}

那我错过了什么?我想我正在做教科书告诉我的一切。

I get this when compiling

希望大家指出我的错误,万分感谢

编辑:@linuxuser27 帮助我解决了我的问题,所以基本上我只是移动了

 int mob::mob_count = 0; 

从 class 定义到 class 实现,像这样:

mob.h:

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;

};

mob.cpp

int mob::mob_count = 0; 

构造函数保持不变。

我假设您在头文件(例如 mob.hpp)中声明 class,然后将头文件包含在多个编译单元(即 cpp 文件)中。基本上是这样的:

main.cpp

#include "mob.hpp" ...

mob.cpp

#include "mob.hpp" ...

从头文件中删除int mob::mob_count = 0;并将其放入mob.cpp