C ++二进制文件的操作数无效

时间:2012-06-06 22:14:32

标签: c++ operands

我是C ++的初学者,我遇到了这段代码的问题,应该在Superbowl决赛中显示分数:

#include <iostream>

enum POINTS { EXTRA_POINT = 1, SAFETY = 2, FIELD_GOAL = 3, TOUCHDOWN =6 };

unsigned short giantsScore = 0, patriotsScore = 0;

int main()
{
std::cout << " Giants: " << giantsScore << "\n";
std::cout << " Patriots: " << patriotsScore << "\n\n";

std::cout << " Giants: " << giantsScore = giantsScore + SAFETY << "\n";
std::cout << " Patriots: " << patriotsScore << "\n\n"; 

std::cout << " Giants: " << giantsScore = giantsScore + TOUCHDOWN + EXTRA_POINT << "\n";
std::cout << " Patriots: " << patriotsScore << "\n\n";

std::cout << " Giants: " << giantsScore << "\n";
std::cout << " Patriots: " << patriotsScore = patriotsScore + FIELD_GOAL << "\n\n";

std::cout << " Giants: " << giantsScore << "\n";
std::cout << " Patriots: " << patriotsScore = patriotsScore + TOUCHDOWN + EXTRA_POINT << "\n\n";

std::cout << " Giants: " << giantsScore << "\n";
std::cout << " Patriots: " << patriotsScore = patriotsScore + TOUCHDOWN + EXTRA_POINT  << "\n\n";

std::cout << " Giants: " << giantsScore = giantsScore + FIELD_GOAL << "\n";
std::cout << " Patriots: " << patriotsScore << "\n\n";

std::cout << " Giants: " <<  giantsScore = giantsScore + FIELD_GOAL << "\n";
std::cout << " Patriots: " << patriotsScore << "\n\n";

std::cout << " Giants: " << giantsScore << "\n";
std::cout << " Patriots: " << patriotsScore = patriotsScore + FIELD_GOAL + EXTRA_POINT  << "\n\n";

return 0;
}

忽略这是非常不优雅的,当我通过编译器,G ++运行时,我收到错误消息

  

错误:类型'int'和'const char [2]'到二进制'运算符&lt;&lt;'

的操作数无效

如果我删除常量并在每个std::cout之前添加它们,那么它运行正常。我只是想知道为什么我不能在每个输出行中添加常量?

2 个答案:

答案 0 :(得分:2)

您的错误消息指出:int << char,这当然是一个奇怪的操作。

这是因为运营商的优先事项。

每个运算符都具有优先级,这意味着它将在评估其他运算符之前或之后进行评估。

+=

之前进行评估

<<应在= cout<<"stuff"成为其原始目的后进行评估。

<<最初是位移运算符(仍然是),因此这就是您遇到这种奇怪行为的原因。添加括号,你会很好。

答案 1 :(得分:1)

检查http://cs.smu.ca/~porter/csc/ref/cpp_operators.html以获取运营商优先级规则的概述。当你这样写:

std::cout << " Patriots: " << patriotsScore = patriotsScore + FIELD_GOAL + EXTRA_POINT  << "\n\n";

然后根据优先级规则,首先执行+运算符,为您提供:

std::cout << " Patriots: " << patriotsScore = result  << "\n\n";

然后&lt;&lt;运算符被执行,这也意味着`result&lt;&lt; “\ n \ n”。但是这个运算符没有在int和char [2]之间定义。

要解决您的问题,请在赋值操作周围加上括号,如下所示:

std::cout << " Patriots: " << (patriotsScore = patriotsScore + FIELD_GOAL + EXTRA_POINT)  << "\n\n";