宏参数顺序很重要

Macros argument order matters?

本文关键字:顺序 参数      更新时间:2023-10-16

当我编译下面的程序时,编译器产生错误。

example.cpp:12:13: error: invalid operands to binary expression ('const char *' and 'const char *')
cout << JMP(to_string(10)) << endl;
        ^~~~~~~~~~~~~~~~~~
example.cpp:6:34: note: expanded from macro 'JMP'
#define JMP(add) "DEFAULT is : " + DEFAULT + " JMP is : " + add
           ~~~~~~~~~~~~~~~ ^ ~~~~~~~
#include <iostream>
#include <string>
#define DEFAULT "00000"
#define JMP(add) "DEFAULT is : " + DEFAULT + " JMP is : " + add
using namespace std;
int main()
{
   cout << JMP(to_string(10)) << endl;
   return 0;
}

而下面的程序可以正确编译

#include <iostream>
#include <string>
#define DEFAULT "00000"
#define JMP(add) "JMP is : " + add + "DEFAULT is : " + DEFAULT
using namespace std;
int main()
{
   cout << JMP(to_string(10)) << endl;
   return 0;
}

为什么宏体中的参数顺序很重要?

尝试去掉+来连接字符数组字面量:

#define JMP(add) "DEFAULT is : " DEFAULT " JMP is : " add

注意:由于add将从您的样本扩展到std::string值(to_string(10)),因此这也不起作用。您需要像这样调用宏:

cout << JMP("10") << endl;

另一种解决方案是使部件成为std::string实例:

#define JMP(add) std::string("DEFAULT is : " DEFAULT " JMP is : ") + add

该错误告诉您,给定给二进制表达式的操作数(即+ operator)不是预期的类型。该操作符至少有一个操作数需要const string &(或者使用c++ 11时需要string &)。加上从左到右的求值就是当你改变顺序时它能工作的原因。

cout << to_string(10) + " is the JUMP" << endl; // having valid operands, + operator returns a string object
cout << "JUMP is : " + to_string(10) << endl;   // same here
cout << "DEFAULT is : " + "00000" << endl;      // no bueno: both operands are const char pointers

如果您有一个const string &作为启动器*,您可以整天保持连接const char * s:

cout << "JUMP is : " + to_string(10) + " DEFAULT is : " + "00000" + "game is " + "concentration, " + "category is " + "..." << endl;

所以,这实际上与宏参数的顺序无关,而是与字符串、char指针、连接、结合性和操作符有关。

*在体育比赛中