Why in conditional operator (?:), second and third operands must have the same type?

后端 未结 5 1381
挽巷
挽巷 2021-01-31 19:35

Why in conditional operator(?:), second and third operands must have the same type?

My code like this:

#include 

        
5条回答
  •  既然无缘
    2021-01-31 19:46

    You should try to decompose what's happening to understand:

    cout << ( a>b ? "a is greater\n" : b );
    

    This translates to :

    operator<<(cout, ( a>b ? "a is greater\n" : b ));
    

    At that stage the compiler must choose one of the following overloads:

    ostream& operator<<(ostream&, int);
    ostream& operator<<(ostream&, const char*);
    

    But it can't because the type of result of the ternary operator is not known yet (only at runtime).

    To make things clearer think like this:

     auto c = a>b ? "test" : 0;
    

    What would be the type of c ? It can't be decided at compile time. C++ is a statically typed language. All types must be known at compile time.

    EDIT:

    You are thinking of a ? b : c in the following way:

    if (a)
        b;
    else
        c;
    

    While it is actually this:

    if (a)
        return b;
    else
        return c;
    

提交回复
热议问题