一個類中靜態容器對象的初始化問題

某網友問:

一個類中,有一個成員變量static set<int> SET,怎麼用一個1000個元素給它初始化?

 

一個類中特殊的成員變量的初始化是非常需要技巧的事情,以前針對這個問題專門寫過一篇博文:

特殊數據類型成員變量的初始化

但這篇博文,並沒有包括上面那位網友提出的問題,爲此給出以下代碼:

#include <set>
#include <iostream>
using namespace std;

class Test
{
private:
	static set<int> SET;
public:
	static void print()
	{
		for(set<int>::iterator iter = SET.begin(); iter != SET.end(); ++iter)
		{
			cout << *iter << endl;
		}
	}
};

set<int> init()
{
	set<int> tmp;
	for(int i = 0; i < 1000; ++i)
	{
		tmp.insert(i);
	}
	return tmp;
}

set<int> Test::SET(init());		// 注意前面必須要有set<int>

int main(int argc, char** argv)
{
	Test::print();

	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章