宏观论证顺序很重要?

时间:2014-03-22 13:39:13

标签: c++ macros

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

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

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

2 个答案:

答案 0 :(得分:1)

尝试摆脱+以连接char数组文字:

#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

答案 1 :(得分:0)

错误告诉您给二进制表达式(即+ operator)的操作数不是预期类型。对于至少一个操作数,此运算符期望const string &(或string &使用C ++ 11)。加上左右评价是为什么它在你切换订单时有效。

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 *

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

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

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