gpt4 book ai didi

C++ 二进制操作数无效

转载 作者:行者123 更新时间:2023-11-30 03:01:37 25 4
gpt4 key购买 nike

我是 C++ 的初学者,我在使用这段代码时遇到问题,该代码应该在 super 碗决赛期间显示比分:

#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++ 运行它时,我收到错误消息

error: invalid operands of types 'int' and 'const char [2]' to binary 'operator<<'

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

最佳答案

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

这是因为运营商的优先级。

每个运算符都有一个优先级,这意味着它将在其他运算符求值之前或之后求值。

+= 之前评估

<<应该在 = 之后评估有cout<<"stuff"是其最初的目的。

<<最初是位移运算符(现在仍然是),所以这就是您遇到这种奇怪行为的原因。添加括号就可以了。

关于C++ 二进制操作数无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10923079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com