1

在这里向您展示我的意思,如果没有代码就很难描述:

class Object
{ 
      // attributes..
};

class Attribute
{
    public:
    void myfunc(); 
};

class Character: public Object, public Attribute
{ 

};

void main()
{
    Object* ch = new Character;
    // How can I call the myfunc() from Attribute
    // tried static_cast<Attribute*>(ch);
}

我只有一个对象类指针,我不知道它是字符对象还是继承自属性类的另一个对象,我知道该类继承自属性类。

4

2 回答 2

3

交叉投射只能由 dynamic_cast 完成。

Object * o = new Character;
Attribute * a = dynamic_cast<Attribute*>(o);

if (!a) throw_a_fit();

a->myfunc();

但是,要使其工作,您必须具有多态基类(它们必须至少具有一个虚函数)。

于 2012-05-20T15:52:57.610 回答
2

如果你知道你有一个正确类型的对象,你可以显式地强制转换:

Object * ch = /* something that's a Character */

static_cast<Attribute *>(static_cast<Character *>(ch))->myfunc();

显然,如果 指向的最衍生对象ch的类型不是 的子类型,这将是不正确的Attribute

If your class hierarchy is polymorphic (i.e. has at least one virtual function in each base class that you care about), then you can use dynamic_cast directly at runtime and check if it succeeded, but that is a comparatively expensive operation. By contrast, the static cast does not incur any runtime cost at all.

于 2012-05-20T16:01:48.277 回答