2017-03-07 87 views
0

當我在宏內部使用a->url時,它失敗了,但是當我替換a->url並且手動輸入字符串時,它可以工作。我如何使a->url與宏兼容?C++ - 爲什麼在使用宏時此代碼無法工作?

g++ -c -g -std=c++11 -MMD -MP -MF "build/Debug/GNU-MacOSX/main.o.d" -o build/Debug/GNU-MacOSX/main.o main.cpp 
main.cpp:18:35: error: expected ';' after expression 
    cout << MANIFEST_URL(a->url); 

CODE:

#include <iostream> 
#include <ctime> 
#include <string> 
using namespace std; 

#define MANIFEST_URL(REPLACE) "https://" REPLACE "/manifest.json"; 

typedef struct custom { 
    char *id; 
    string url; 
    custom *next; 
} custom; 

int main() { 
    custom *a; 
    a = new custom; 
    a->url = "www.google.com"; 
    cout << MANIFEST_URL(a->url); 
    cout << a->url; 
    return 0; 
} 
+9

想一下宏擴展,如果直接寫而不是宏,它真的有效嗎? –

+2

還要記住,預處理是與實際編譯分開的一個步驟。預處理器對你的結構或變量一無所知。 –

+3

而不是一個宏,定義一個使用字符串連接的函數。 –

回答

5

注刪除;在宏定義結束)

如果運行g++ -E你可以看到預處理器的輸出。 #define s爲只是文本替換,所以當你有

MANIFEST_URL(a->url) 

將擴大到

"https://" a->url "/manifest.json" 

這個宏的目的顯然是要用於字符串中使用,如果你這樣做:

MANIFEST_URL("www.google.com") 

它擴展到

"https://" "www.google.com" "/manifest.json" 

相鄰串文字是由編譯器連接在一起,所以如果你想這與std::string或c串char*標識工作,只是定義一個函數來進行上述相當於

"https://www.google.com/manifest.json" 

std::string manifest_url(const std::string& replacement) { 
    return "https://" + replacement + "/manifest.json"; 
} 
6

你的宏擴展到這一點:

cout << "https://" a->url "/manifest.json";; 

這顯然是無效的。

相關問題