gcc inconsistent about string type [duplicate]

2019-09-11 09:32发布

问题:

This question already has an answer here:

  • Conditional operator used in cout statement 2 answers

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