将对象转换为Base类型会创建重复的变量值

时间:2014-12-06 05:27:19

标签: c++ oop object casting derived-class

如何防止基类变量具有不同的值?将对象转换为基类会给我一个不同的值。

class BaseClass
{
    int baseClassVariable;
    BaseClass()
    {
        baseClassVariable = randint();
    }
}

class Derived : public BaseClass
{
}

main()
{
    Derived* D = new Derived();
    BaseClass* bc = (BaseClass*)D;

    //D->baseClassVariable is not the same as bc->baseClassVariable
    print(D->baseClassVariable); 
    print(bc->baseClassVariable);
}

`

0 个答案:

没有答案