预处理命令中的#和##

来源:互联网 发布:java多线程异步调用 编辑:程序博客网 时间:2024/04/28 01:10

在c/c++的程序设计中,有的时候不免要实现某些对象转换出相应名字字符串或两对象名直接相连的情况,这时候可采用宏定义中加入#和##分别实现相应功能。下面是摘抄的一段解释。

 

The # and ## preprocessor operators are used with the #define preprocessor directive.

  • Using # causes the first argument after the # to be returned as a string in quotes.
  • Using ## concatenates what's before the ## with what's after it.

For example, the command

     #define to_string( s ) # s

will make the compiler turn this command

     cout << to_string( Hello World! ) << endl;

into

     cout << "Hello World!" << endl;

Here is an example of the ## command:

     #define concatenate( a, b ) a ## b     ...     int xy = 10;     ...

This code will make the compiler turn

     cout << concatenate( x, y ) << endl;

into

     cout << xy << endl;

which will, of course, display '10' to standard output.