不,每个实例GameObject
都有自己的(未初始化的)实例id
。需要有一个id
可用于所有GameObject
. 实现这一点的一种机制是使用static
类变量。如果涉及线程,则需要同步对static
变量的访问:
class GameObject
{
protected:
static int id;
};
int GameObject::id; // defaults to zero and should be added to
// exactly one .cpp file only.
GameObject::GameObject() : instances(GameObject::id++) {}
另一种选择是使用boost::uuid
:
#include <string>
using std::string;
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
using boost::lexical_cast;
using boost::uuids::uuid;
using boost::uuids::random_generator;
class GameObject
{
public:
string instances;
GameObject() : instances(make_uuid_());
void Display();
private:
string make_uuid_()
{
return lexical_cast<string>((random_generator())());
}
};