繁体   English   中英

宏参数顺序很重要吗?

[英]Macros argument order matters?

当我编译以下程序时,编译器会生成以下错误。

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 &作为starter* ,你可以整天连接const char * s:

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

所以,这实际上不是关于宏参数的顺序,而是关于字符串、字符指针、连接、结合性和运算符。

*就像在体育比赛中一样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM