将转换对象键入子类对象

时间:2013-11-18 09:17:53

标签: c++ casting virtual virtual-inheritance typecasting-operator

我想将对象hlaObj从RtiValueAggregate转换为HlaObject,但它不起作用......!两个类之间没有继承。和HlaObject实际上来自RtiValue。 谁能告诉我以下代码有什么问题: 谢谢!

class RtiValue;
class HlaObject;

class RtiValueAggregate 
{
public:
    friend class RtiValue;
    int w;

    RtiValueAggregate() : w(10)
    {        
    }

};


class RtiValue
{
public:
    friend class RtiValueAggregate;

    RtiValue()
    {
        int x = 5;
        pAggregate_ = new RtiValueAggregate();
    }

    RtiValueAggregate* getAggregate() const
    {
        return pAggregate_;
    }

private:
    RtiValueAggregate* pAggregate_;
};


class ObjectAttribute : public RtiValue
{
public:
    int v;

    ObjectAttribute() : v(0)
    {
        RtiValue();
    }        

};


class HlaObject :public virtual RtiValueAggregate
{
public:
    int a;
    ObjectAttribute* ptrV;

    HlaObject() : a(1)
    {
        ptrV = new ObjectAttribute();
    }

};


int _tmain(int argc, _TCHAR* argv[])
{
    RtiValue *rtiVal = new RtiValue();
    RtiValueAggregate* rtiValueAggr = rtiVal->getAggregate();
    HlaObject *hlaObj = reinterpret_cast<HlaObject*>(rtiValueAggr);

    cout << "Press any key to exit..." << endl;
    cin.get();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

使用dynamic_cast,绝不使用reinterpret_cast

顺便说一句,为什么这样做:

class HlaObject :public virtual RtiValueAggregate

而不是:

class HlaObject :public RtiValueAggregate