我有一个包含两个私有int的类,一个是const(m_id),另一个是static(next_id)。
我想在每次创建类的对象时将m_id设置为next_id并增加next_id。
但是因为它是一个const我不能这样设置它:
Class::Class()
{
m_id = next_id++;
}
我需要像那样设置它
Class::Class() :m_id(next_id)
{
next_id++;
}
但这并不好,因为我不能像那样访问私有静态。
有人告诉我,const并不打算用于此,所以只需删除它。这真的是唯一的解决方案吗?
编辑:这里是完整的标题和来源
头
#ifndef ENTITY_H_LEA12OED
#define ENTITY_H_LEA12OED
#include "EntityKey.h"
#include "ComponentManager.h"
class Entity
{
public:
Entity ();
virtual ~Entity ();
private:
ekey m_key;
ComponentManager m_componentManager;
const int m_id;
static int next_id;
};
#endif /* end of include guard: ENTITY_H_LEA12OED */
源
#include "Entity.h"
Entity::Entity() :m_id(next_id++)
{
}
Entity::~Entity()
{
}
(当然EntityKey和ComponentManager与我的问题无关)
(编辑2:因测试而纠正了代码中的一些错误)
答案 0 :(得分:2)
您需要定义next_id
,否则它将编译,但不是链接。像这样:
class Class
{
/* whatever */
};
Class::Class() :m_id(next_id++)
{
/* whatever */
}
int Class::next_id = 0;