2015-10-30 54 views
1

我看到人們使用反斜線時,他們中的宏定義功能:定義函數++

#define ClassNameNoDebug(TypeNameString)         \ 
    static const char* typeName_() { return TypeNameString; }     \ 
    static const ::Foam::word typeName 

我做了一個非常簡單的測試。但是我收到了一堆錯誤。測試代碼如下: 在我testmacro.h文件:

#define declearlarger(first,second)               \ 
    double whichislarger(double first,double second){ return (first>second) ? fisrt : second;} 

在我的main()函數:

int second =2; 
int first =1; 

cout << declearlarger(first,second) << endl; 

的錯誤是:

/home/jerry/Desktop/backslash/backslash_test/testmacro.h:7: error: expected primary-expression before 'double' 
    double whichislarger(double first,double second){ return (first>second) ? fisrt : second;} 
    ^
/home/jerry/Desktop/backslash/backslash_test/testmacro.h:7: error: expected ';' before 'double' 
    double whichislarger(double first,double second){ return (first>second) ? fisrt : second;} 
    ^
/home/jerry/Desktop/backslash/backslash_test/main.cpp:24: error: expected primary-expression before '<<' token 
    cout << declearlarger(first,second) << endl; 
             ^

這一切結束我的測試錯誤。任何人都可以提出一些建議,爲什麼這些錯誤彈出?

+0

你的宏定義了一個函數;它並沒有稱之爲獲得價值。你不能使用'<<'運算符將函數定義重定向到'cout'。它在C++中沒有任何意義。另外,'fisrt'。 – crayzeewulf

+0

'fisrt'有什麼好笑的?我在Wome有一個叫做'fisrt'的vewy gweat fwiend! – user4581301

+0

Touché,@ user4581301。 – crayzeewulf

回答

3

您正試圖在表達式中使用函數定義(由您的宏生成)。 C++不允許這樣的事情。您可以改爲將您的宏定義爲:

#define declearlarger(first,second) \ 
     (((first)>(second)) ? (first) : (second)) 

然後它就可以工作。另請注意,沒有任何錯誤來自反斜槓,它們都是由於函數定義/表達式衝突而生成的。