Compiler error for conditional operator “?:” when used with typecasting operator

前端 未结 3 1359
囚心锁ツ
囚心锁ツ 2021-02-14 19:43

Following code is in simplest form:

struct X {
  operator char () const { return \'a\'; }
};

int main ()
{
  X obj, *p = &obj;
  char a = *p;  // ok
  char          


        
3条回答
  •  耶瑟儿~
    2021-02-14 20:33

    The error is correct. operands to ?: have different types: ‘X’ the first, and ‘char’ the second. The compiler cannot know that you want the expression to be a char in the end - that will happen later, after the evaluation of the whole expression (true)? *p : 'z'; - an evaluation which cannot be done in the first place due to type discrepancies.

提交回复
热议问题