【问题标题】:How I can auto increment each class objects?如何自动递增每个类对象?
【发布时间】:2013-07-25 12:20:59
【问题描述】:

我有一个包含两个私有 int 的类,一个是 const (m_id),另一个是静态 (next_id)。

我想在每次创建类的对象时将 m_id 设置为 next_id 并递增 next_id。

但由于它是一个常量,我不能这样设置:

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:纠正了由于测试导致的代码中的一些错误)

【问题讨论】:

  • “我不能像那样访问私有静态”是什么意思?也许你应该发布一个完整的代码示例。

标签: c++ class static private increment


【解决方案1】:

你需要定义next_id,否则它会编译,但不能链接。像这样:

class Class
{
    /* whatever */
};

Class::Class() :m_id(next_id++)
{
    /* whatever */
}

int Class::next_id = 0;

【讨论】:

  • 谢谢(将next_id声明为0),没想到会这样
猜你喜欢
  • 1970-01-01
  • 2020-10-17
  • 2012-02-08
  • 1970-01-01
  • 2016-03-07
  • 1970-01-01
  • 2015-07-21
  • 1970-01-01
  • 2020-10-27
相关资源
最近更新 更多