C ++ - 为什么使用宏时此代码不起作用?

时间:2017-03-07 22:30:05

标签: c++ macros

当我在宏中使用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);

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;  
}

2 个答案:

答案 0 :(得分:6)

你的宏扩展到这个:

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

显然无效。

答案 1 :(得分:5)

注意删除宏定义末尾的;

如果运行g++ -E,您可以看到预处理器的输出。 #define只是文字替换,所以当你有

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字符串char*标识符,只需定义一个函数来执行此操作:

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