C - 当使用宏时,为什么此代码不起作用
C++ - why is this code not working when a macro is used?
当我在宏内使用 a->url
时,它会失败,但是当我替换 a->url
并手动将字符串放入时。如何使a->url
与宏兼容?
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);
代码:
#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;
}
您的宏向此扩展:
cout << "https://" a->url "/manifest.json";;
显然无效。
(请注意,在宏定义末尾删除;
)
如果运行g++ -E
,则可以看到预处理器的输出。 #define
s只是文本替换,所以当您拥有
MANIFEST_URL(a->url)
它将扩展到
"https://" a->url "/manifest.json"
显然要与字符串文字一起使用,如果您这样做:
MANIFEST_URL("www.google.com")
它扩展到
"https://" "www.google.com" "/manifest.json"
相邻字符串文字由编译器加入,因此上述等同于
"https://www.google.com/manifest.json"
如果您希望与std::string
或C String char*
标识符一起使用,请定义一个功能:
std::string manifest_url(const std::string& replacement) {
return "https://" + replacement + "/manifest.json";
}
相关文章:
- 与C代码相比,为什么C++代码不需要"#define _POSIX_C_SOURCE 200809L"?
- 为什么代码给出分段错误?
- 不理解为什么代码没有产生所需的答案
- 为什么代码段会引发浮点异常?
- 我不确定为什么代码没有运行,它在编译时抛出错误,说它无法找到 PrintArray()
- 为什么代码会崩溃?(在CPP中)
- 为什么代码使用 std::map 无法编译?
- 为什么代码会抛出非法内存访问错误
- 为什么代码不能返回正确的值?
- 为什么 C++ 代码实现的性能不比 python 实现更好?
- 为什么代码告诉我vectorsubsibrtion超出了范围
- 字符指针值为空白,为什么代码不打印5
- 为什么代码中没有处理每个逗号字符?
- 为什么代码在输入大于10的输入上会分割故障
- 为什么C++代码不起作用(strncpy_s)?
- 为什么代码无法打印此 2D 数组的元素?
- 为什么代码没有cout?
- 为什么代码中的模板参数推导/替换失败?-.
- 为什么代码在 c++ 中无法正常运行
- 在C++中,为什么代码示例在重载运算符时经常使用内存位置