铸造工作后为什么不分配此作业?

时间:2018-07-06 21:38:45

标签: c++ class inheritance casting

通过指针时,我可以通过赋值进行赋值,但是我只是想知道为什么最后一个示例不起作用:

struct BaseClass
{
    int a = 0;
};

struct DerivedClass : BaseClass
{
    int b = 0;
};

int main()
{
    BaseClass base{};
    DerivedClass derived{};
    base.a = 7;

    BaseClass* ptrToBase = &derived;
    *ptrToBase = base;  // WORKS, changes 'a' variable to 7

    *(static_cast<BaseClass*> (&derived)) = base; // WORKS, changes 'a' variable to 7

    (static_cast<BaseClass>(derived)) = base; // Doesn't work, doesn't change 'a' variable to 7
}

0 个答案:

没有答案