c++解决枚举类型不能重名的宏

本文介绍了一种在C++中通过宏来解决枚举类型中元素重名问题的方法,提供了具体的使用示例,帮助开发者规避命名冲突。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#define ENUM_DECLARE(class_type, enum_type) \
	public: \
	enum_type value; \
	operator enum_type(){return value;} \
	class_type(){} \
	class_type(int val){ value = (enum_type)val;} \
	class_type(const enum_type& n):value(n){}


用法示例:

#include <iostream>
using namespace std;

     
#define ENUM_DECLARE(class_type, enum_type) \
	public: \
	enum_type value; \
	operator enum_type(){return value;} \
	class_type(){} \
	class_type(int val){ value = (enum_type)val;} \
	class_type(const enum_type& n):value(n){}



struct Day
{
	enum _Day
	{
		One = 1,
		Two,
		Three
	};
	ENUM_DECLARE(Day, _Day)
};

struct Night
{
	enum _Night
	{
		One = 1,
		Two,
		Three,
		Four
	};

	ENUM_DECLARE(Night, _Night)
};


void test(Night n)
{
	cout << n << "in test"<<endl;
}

void test_day(Day d)
{
	cout << d << "in test"<<endl;
}

int main()
{
	Night night;
	night = Night::One;

	cout <<night<<endl;

	if(night == 1)
		cout <<"assert(night ==1)"<<endl;
	else
		cout <<night<<endl;

	int a = (int)night;
	cout <<"a = " <<a<<endl;

	enum aa{b, cc};
	aa bb;
	bb=(aa)3;

	night = (int)4;
	night = 4; //超出的权限
	//bb = 4; //error

	if(night == Night::Four)
		cout <<"Four"<<endl;
	else
		cout <<night<< "== "<<endl;

	test(night);
	test(Night::One);
	test(Night::Two);

	cout <<"xxx"<<endl;
	Day day;
	day = Day::One;
	cout <<day<<endl;

	test_day(Day::Three);
	test_day(day);



	char c; 
	cin>>c;

	return 0;
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值