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;

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

从类定义到类实现,如下所示:

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;

};

暴民.cpp

int mob::mob_count = 0; 

构造函数保持不变。

4

1 回答 1

0

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

主文件

#include "mob.hpp" ...

暴民.cpp

#include "mob.hpp" ...

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

于 2017-03-25T20:39:16.797 回答