【问题标题】:How to speak to a inherit class from another inherit class如何与另一个继承类的继承类对话
【发布时间】:2012-05-20 15:36:41
【问题描述】:
在这里向您展示我的意思,如果没有代码就很难描述:
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);
}
我只有一个对象类指针,我不知道
如果它是一个字符对象或另一个继承自
属性类,我知道的是类继承自属性类。
【问题讨论】:
标签:
c++
function
inheritance
【解决方案1】:
交叉投射只能通过dynamic_cast来完成。
Object * o = new Character;
Attribute * a = dynamic_cast<Attribute*>(o);
if (!a) throw_a_fit();
a->myfunc();
但是,要使其工作,您必须具有多态基类(它们必须至少具有一个虚函数)。
【解决方案2】:
如果你知道你有一个正确类型的对象,你可以显式地强制转换:
Object * ch = /* something that's a Character */
static_cast<Attribute *>(static_cast<Character *>(ch))->myfunc();
如果ch 指向的最衍生对象的类型不是Attribute 的子类型,这显然是不正确的。
如果你的类层次结构是多态的(即在你关心的每个基类中至少有一个虚函数),那么你可以在运行时直接使用dynamic_cast 并检查它是否成功,但这是一个相对昂贵的操作.相比之下,静态转换根本不会产生任何运行时成本。