gcc inconsistent about string type [duplicate]

£可爱£侵袭症+ 提交于 2019-12-25 03:52:28

问题


I have the following test program:

#include <string>
#include <iostream>

int main()
{
    std::string s;
    std::string a = "sd";

    std::cout << a==s ? "y" : "n";

    return 0;
}

Trying to compile this with g++ test.cpp gives the following cryptic error:

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";
                ^

It seems that s is being correctly compiled as type std::string, while a is being compiled as std::basic_ostream<char>!? HELP!!


回答1:


The compiler parsed your statement as ((std::cout << a) == s) ? "y" : "n"; because of operators precedence : You need parentheses.

std::cout << (a==s ? "y" : "n");



回答2:


The error message from the compiler is very helpful here. It's saying the LHS of the operator is of type std::basic_ostream<char> while the RHS of the operator is of type std::string {aka std::basic_string<char>}.

i.e. the line

std::cout << a==s ? "y" : "n";

is being interpreted as

(std::cout << a) == s ? "y" : "n";

To change the compiler to take the right objects for the == operator, you'll have to use parantheses to override that behavior.

std::cout << (a==s ? "y" : "n");


来源:https://stackoverflow.com/questions/25558482/gcc-inconsistent-about-string-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!