C - 当使用宏时,为什么此代码不起作用

C++ - why is this code not working when a macro is used?

本文关键字:为什么 代码 不起作用      更新时间:2023-10-16

当我在宏内使用 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";
}