C++ - 为什么在使用宏时此代码无法工作?
问题描述:
当我在宏内部使用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;
}
答
(注删除;
在宏定义结束)
如果运行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";
}
答
你的宏扩展到这一点:
cout << "https://" a->url "/manifest.json";;
这显然是无效的。
想一下宏扩展,如果直接写而不是宏,它真的有效吗? –
还要记住,预处理是与实际编译分开的一个步骤。预处理器对你的结构或变量一无所知。 –
而不是一个宏,定义一个使用字符串连接的函数。 –