Casting pointers and the ternary ?: operator. Have I reinvented the wheel?

前端 未结 4 1579
无人共我
无人共我 2021-02-14 04:19

The last line of this code fails to compile with castingAndTernary.cpp:15: error: conditional expression between distinct pointer types ‘D1*’ and ‘D2*’ lacks a cast

4条回答
  •  旧巷少年郎
    2021-02-14 05:04

    The [ternary] conditional operator requires its second and third operands to have the same type.

    b = boolean_expression ? new D1 : new D2;
    

    You have the distinct types D1* and D2*. As the error message indicates, you have to ensure the correct type with an explicit conversion (i.e. a cast):

    b = boolean_expression ? static_cast(new D1) : static_cast(new D2);
    

    The standard says that compilers must require this (instead of just doing an implicit conversion), so that's what your compiler requires.

提交回复
热议问题