[C++]位元運算與枚舉

位元運算與枚舉

舊思維: Enum 以 0,1,2,3,4,5,6

新思維: Enum 以 0,1,2,4,8,16,32

這種設計可以發現當轉為二進制時,只有一個位數為1,其餘為0。

使用方式:

宣告列舉變數 obj 

Set值 : 使用 | 

Get值 : 使用 &

void Demo_BitEnum();

int main(){

	Demo_BitEnum();
	return 0;
}

enum AlignDir
{
	// comboboxH: Left, CenterH, Right
	// comboboxV: Top, CenterV, Bottom
	AlNone    = 0,     // 0000 0000
	AlLeft    = 1 << 1,// 0000 0001
	AlTop     = 1 << 2,// 0000 0010
	AlRight   = 1 << 3,// 0000 0100
	AlBottom  = 1 << 4,// 0000 1000
	AlCenterH = 1 << 5,// 0001 0000
	AlCenterV = 1 << 6 // 0010 0000 
};

void Demo_BitEnum()
{
	// invalid conversion from 'int' to 'AlignDir' ,故需轉型
	enum AlignDir pos = static_cast<AlignDir>(AlRight | AlCenterV); // 水平Right, 垂直Center
	if((pos & AlRight) == AlRight)
	{
		cout << "水平Right" << endl;
	}
	if((pos & AlCenterV) == AlCenterV)
	{
		cout << "垂直Center" << endl;
	}
}