Ternary operator implicit cast to base class

前端 未结 4 1961
我在风中等你
我在风中等你 2020-12-28 12:15

Consider this piece of code:

struct Base
{
    int x;
};

struct Bar : Base
{
    int y;
};

struct Foo : Base
{
    int z;
};

Bar* bar = new Bar;
Foo* foo          


        
4条回答
  •  死守一世寂寞
    2020-12-28 12:40

    In other words, why does Base* obj = foo; work without a cast but using the ?: operator doesn't?

    The type of the conditional expression does not depend on the what it is assigned to. In your case, the compiler needs to be able to evaluate !bar ? foo : bar; regardless of what it is assigned to.

    In your case, that is a problem since neither foo converted to type of bar nor bar can be converted to type of foo.

    Is it because it's not clear that I want to use the Base part?

    Precisely.

提交回复
热议问题