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

来源:互联网 发布:工程软件管理 编辑:程序博客网 时间:2024/05/17 08:15

 有如下C++代码:

[cpp] view plain copy
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. #define A(exp) cout << "I am "#exp << endl;  
  5. #define B(exp) cout << sz##exp << endl;  
  6. #define C(exp) cout << #@exp << endl;  
  7.   
  8. int main()  
  9. {     
  10.     char *szStr = "test";  
  11.     A(Chinese); // cout << "I am ""Chinese" << endl;  
  12.     B(Str);     // cout << szStr << endl;  
  13.     C(a);       // cout << 'a' << endl;  
  14.     C(ab);      // cout << 'ab' << endl;  
  15.   
  16.     return 0;  
  17. }  

  运行结果如下:

  

  展开的时候,#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:

[cpp] view plain copy
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. #ifdef ASSERT  
  5. #undef ASSERT  
  6. #endif  
  7. #define ASSERT(exp)\  
  8.     if (!(##exp))\  
  9.     {\  
  10.         cout << "an error occured while execute \""#exp"\" at "\  
  11.              << __FILE__ << "(" << __LINE__ << ")" << endl;\  
  12.         exit(-1);\  
  13.     }  
  14.   
  15. int main()  
  16. {     
  17.     int a = 0;  
  18.     int b = 1;  
  19.   
  20.     ASSERT(a == b);  
  21.   
  22.     cout << "test" << endl;  
  23.   
  24.     return 0;  
  25. }  
  结果如下:

  


http://blog.csdn.net/beanjoy/article/details/7577944

0 0
原创粉丝点击