標籤

C++ (12) Linux (6) MacOSX (4) Makefile (3) Matlab (3) Ubuntu (3) Android (2) C (1) Refactoring (1)

2011年9月30日 星期五

[C語言] #define

常見的就不多說了
下面列了幾個每次都會忘記的用法...囧


#define CONCAT(x,y) x##y      // concatenate x & y
#define ToChar(x) #@x            // change x into char
#define ToString(x) #x              // change x into string




x##y 就是把x和y連接在一起
比如說:
int n = CONCAT(29979, 2458);      // 結果就是 n = 299792458(光速)\


再來是 #@x
其作用就是幫x用單引號包起來
並返回一個const char,比如說:
char a = ToChar(3);                       // 結果就是 a = '3'



而 #x 則是幫x加上雙引號,例如:
char* str = ToString(123132);        // str 就變成 "123123" 
不過這時候compiler可能會發出類似以下的warning


warning: deprecated conversion from string constant to ‘char*’


原因是"123123"是const char*而str是char*
如果不小心透過str去改道const char* ("123123")裡的東西
可能就會發生意想不到的事情
讓compiler不要該的方法就是在char* str前面加上const變成
const char* str = ToString(123123);




最後把之前上「資料結構與程式設計」這門課時
Ric使用的多行define的方法給PO上來,例如:


#define regNewBaseClass(BaseClass)  \
class BaseClass: public SuperClass {    \
public:                                                      \
   BaseClass();                                        \
   ~BaseClass();                                      \
private:                                                    \
   // TODO add template private              \
   // data members here...                        \
}


多行的define要在每一次換行時
在最後面加上反斜線 \ 告訴compiler後面接的換行是escaped character


這提供了「使用把實作(definition)與宣告(declaration)分開的作法,並大量宣告繼承類別時,會塞滿整個header file造成閱讀與維護上不易」的一個絕佳解決方案。



沒有留言:

張貼留言