c++インプリメンテーションインスタンス化時に各オブジェクトに一意のIDを追加

885 ワード

クラスの静的メンバー変数で実装され、コンストラクション関数に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;
}