我可以获得多态行为,而不使用虚拟函数? [英] Can I get polymorphic behavior without using virtual functions?
问题描述
由于我的设备,我不能使用虚拟功能。假设我有:
class Base
{
void doSomething(){}
} ;
class Derived:public Base
{
void doSomething(){}
};
//在任何地方
{
Base * obj = new Derived;
obj-> doSomething();
}
obj-> doSomething code>将只调用
Base :: doSomething()
调用 我知道我可以在 您可以将基类指针转换为派生类并调用函数。 由于doSomething()没有被声明为virtual,所以应该得到派生实现。 Because of my device I can't use virtual functions. Suppose I have: the Is there a way with I know I can just put a You could down cast the base class pointer to the derived class and call the function. Since doSomething() is not declared virtual, you should get the derived implementation. 这篇关于我可以获得多态行为,而不使用虚拟函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! Derived
?的
doSomething
/ p>
之前放置
虚拟
c> Base
它解决了问题,但我受到我的设备的限制,编译器不支持它。
Base * obj = new Derived;
Derived * d = static_cast< Derived *>(obj);
d-> doSomething();
class Base
{
void doSomething() { }
};
class Derived : public Base
{
void doSomething() { }
};
// in any place
{
Base *obj = new Derived;
obj->doSomething();
}
obj->doSomething()
will call just the Base::doSomething()
Base *obj
, to call the doSomething
of the Derived
?virtual
before doSomething()
of Base
it solve the problem, but I'm limited by my device, the compiler doesn't support it.Base* obj = new Derived;
Derived* d = static_cast<Derived*>( obj );
d->doSomething();