#、##、#@在#define中的用法

  • Post author:
  • Post category:其他


有如下C++代码:

#include <iostream>
using namespace std;

#define A(exp) cout << "I am "#exp << endl;
#define B(exp) cout << sz##exp << endl;
#define C(exp) cout << #@exp << endl;

int main()
{	
	char *szStr = "test";
	A(Chinese);	// cout << "I am ""Chinese" << endl;
	B(Str);		// cout << szStr << endl;
	C(a);		// cout << 'a' << endl;
	C(ab);		// cout << 'ab' << endl;

	return 0;
}

运行结果如下:

展开的时候,#exp被扩展成

字符串

,##exp被扩展成

子串

,#@exp被扩展成

字符



注意:

#@只实用于windows系统

,MSDN如下说明

Operator

Action

Stringizing operator (#)

Causes the corresponding actual argument to be enclosed in double quotation marks

Charizing operator (#@)

Causes the corresponding argument to be enclosed in single quotation marks and to be treated as a character (Microsoft Specific)

Token-pasting operator (##)

Allows tokens used as actual arguments to be concatenated to form other tokens

可用作自定义ASSERT:

#include <iostream>
using namespace std;

#ifdef ASSERT
#undef ASSERT
#endif
#define ASSERT(exp)\
	if (!(##exp))\
	{\
		cout << "an error occured while execute \""#exp"\" at "\
			 << __FILE__ << "(" << __LINE__ << ")" << endl;\
		exit(-1);\
	}

int main()
{	
	int a = 0;
	int b = 1;

	ASSERT(a == b);

	cout << "test" << endl;

	return 0;
}

结果如下:



版权声明:本文为BeanJoy原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。