使用基类指针调用派生类中的非虚函数 [英] Calling a non-virtual function in derived class using a base class pointer
问题描述
如此答案中所述:
高度依赖dynamic_cast常常表明您的设计出现了错误。
我想知道的是如何在派生类中调用自定义函数,在基类中没有同名函数,但使用基类指针,并且可能没有 dynamic_cast
如果实际上有更好的方法。
如果这个函数是一个虚函数定义在这两个,这很容易。
也许 dynamic_cast
是最后的方法吗?
为了调用 Derived
类的函数,指向派生类的指针。作为一个选项(根据情况),你可能想使用 static_cast
而不是 dynamic
,但正如你所说: p>
这通常表示您的设计出错了
此外,有时我认为可以使用casts 。当我为一个游戏设计一个GUI库时,它有一个基类 Widget
和许多子类。在编辑器中创建了一个实际的窗口布局,稍后一些 Loader
类正在扩展此布局。为了从布局中填充窗口小部件实际具体针对每个窗口小部件数据(游戏相关),我做了一个方法从窗口小部件查询窗口小部件的孩子。此函数返回 Widget *
,然后将 dynamic_casted
重新调整为实际类型。我没有找到一个更好的设计。
后来我还发现 Android
上的GUI系统工作方式相同
As noted in this answer:
high reliance on dynamic_cast is often an indication your design has gone wrong.
What I'd like to know is how can I call a custom function in a derived class, for which there is no same-name function in the base class, but do so using a base class pointer and perhaps without dynamic_cast
if in fact there is a better way.
If this function was a virtual function defined in both, that's easy. But this is a unique function only in the derived class.
Perhaps dynamic_cast
is the best way afterall?
In order to call a function of Derived
class you have to obtain a pointer to derived class. As an option (depending on situation) you may want using static_cast
instead of dynamic
, but as you said:
it is often an indication your design has gone wrong
Also, sometimes I think it's ok to use casts. When I was designing a GUI library for a game it has a base class Widget
and lots of subclasses. An actual window layout was made in an editor and later some Loader
class was inflating this layout. In order to fill widgets from the layout with actual specific for each widget data (game related) I made a method for quering widget's child from a widget. This function retuned Widget*
and then I dynamic_casted
it to actual type. I have not found a better design for this.
Later I also found that GUI system on Android
works the same way
这篇关于使用基类指针调用派生类中的非虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!