c++实现在实例化时为每个对象添加唯一ID

用类的静态成员变量实现,在构造函数中增加ID的值,然后析构函数中减小ID的值。这样就保证了每次实例化时的ID唯一。然后将该静态成员变量赋值给私有变量即可。具体代码如下:

类的声明:

#pragma once
#include
class tank
{
public:
	tank();
	~tank();
	void fire();
	static int getCount();
	int getID();
private:
	static int i_count;
	static int g_id;
	int id;
};

类的定义:

#include "stdafx.h"
#include "tank.h"
#include
using namespace std;

int tank::i_count = 10;
int tank::g_id = 0;
tank::tank()
{
	i_count++;
	g_id++;
	cout << "tank" << endl;
}


tank::~tank()
{
	i_count--;
	g_id--;
	cout << "~tank" << endl;
}

void tank::fire()
{
	cout << "fire:" << endl;
}

int tank::getCount()
{	
	return i_count;
}

int tank::getID()
{
	id = g_id;
	return id;
}



你可能感兴趣的:(C++)