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

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

类的声明:

#pragma once
#include<string>
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<iostream>
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;
}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值