1、# (stringizing)字符串化操作符。
其作用是:將宏定義中的傳入參數名轉換成用一對雙引號括起來參數名字符串。其只能用於有傳入參數的宏定義中,且必須置於宏定義體中的參數名前。
如:
#define example(instr) printf("the input string is:\t%s\n",#instr)
#define example1(instr) #instr
當使用該宏定義時:
example(abc); 在編譯時將會展開成:printf("the input string is:\t%s\n","abc");
string str=example1(abc); 將會展成:string str="abc";
注意:
對空格的處理
a.忽略傳入參數名前面和後面的空格。
如:str=example1( abc ); 將會被擴展成 str="abc";
b.當傳入參數名間存在空格時,編譯器將會自動連接各個子字符串,用每個子字符串中只以一個空格連接,忽略其中多餘一個的空格。
如:str=exapme( abc def); 將會被擴展成 str="abc def";
2、## (token-pasting)符號連接操作符
宏定義中:參數名,即爲形參,如#define sum(a,b) (a+b);中a和b均爲某一參數的代表符號,即形式參數。
而##的作用則是將宏定義的多個形參成一個實際參數名。
如:
#define exampleNum(n) num##n
int num9=9;
使用:
int num=exampleNum(9); 將會擴展成 int num=num9;
注意:
1.當用##連接形參時,##前後的空格可有可無。
如:#define exampleNum(n) num ## n 相當於 #define exampleNum(n) num##n
2.連接後的實際參數名,必須爲實際存在的參數名或是編譯器已知的宏定義
3、實際高級應用
.h文件:
gboolean CdkDebug_IsFatalLogEnabled(); gboolean CdkDebug_IsErrorLogEnabled(); gboolean CdkDebug_IsWarnLogEnabled(); gboolean CdkDebug_IsInfoLogEnabled(); gboolean CdkDebug_IsDebugLogEnabled(); gboolean CdkDebug_IsTraceLogEnabled(); gboolean CdkDebug_IsAllLogEnabled();
.cpp文件:
#define CDK_DEFINE_IS_LOG_ENABLED(level) \ gboolean CdkDebug_Is##level##LogEnabled(void) \ { \ return gLogLevel <= Log_##level; \ } CDK_DEFINE_IS_LOG_ENABLED(Fatal) CDK_DEFINE_IS_LOG_ENABLED(Error) CDK_DEFINE_IS_LOG_ENABLED(Warn) CDK_DEFINE_IS_LOG_ENABLED(Info) CDK_DEFINE_IS_LOG_ENABLED(Debug) CDK_DEFINE_IS_LOG_ENABLED(Trace) CDK_DEFINE_IS_LOG_ENABLED(All)