Bar*_*uch 0 c++ gcc ternary-operator stdstring operator-precedence
我有以下测试程序:
#include <string>
#include <iostream>
int main()
{
std::string s;
std::string a = "sd";
std::cout << a==s ? "y" : "n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
尝试编译它g++ test.cpp会产生以下神秘错误:
error: no match for 'operator==' (operand types are 'std::basic_ostream<char>' and 'std::string {aka std::basic_string<char>}')
std::cout << a==s ? "y" : "n";
^
Run Code Online (Sandbox Code Playgroud)
它似乎s被正确编译为类型std::string,而a被编译为std::basic_ostream<char>!?救命!!
((std::cout << a) == s) ? "y" : "n"; 由于运算符优先级,编译器解析了您的语句:您需要括号.
std::cout << (a==s ? "y" : "n");
Run Code Online (Sandbox Code Playgroud)
编译器的错误消息在这里非常有用.它表示运营商的LHS属于类型,std::basic_ostream<char>而运营商的RHS属于类型std::string {aka std::basic_string<char>}.
即线
std::cout << a==s ? "y" : "n";
Run Code Online (Sandbox Code Playgroud)
被解释为
(std::cout << a) == s ? "y" : "n";
Run Code Online (Sandbox Code Playgroud)
要将编译器更改为为==运算符选择正确的对象,您必须使用parantheses来覆盖该行为.
std::cout << (a==s ? "y" : "n");
Run Code Online (Sandbox Code Playgroud)