本文介绍了避免多态性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上课:

------------

class Component {

void setEnabled(bool状态);

}

------------

我想要setEnabled不是虚拟的(有很多成员函数。不是虚拟的有效)。

如果派生类按钮 setEnabled中的多态性是什么?然后在这个函数中:

------------

void func(Component& a){

a.setEnabled(true);

}

------------

不会被称为b $ b Button.setEnabled"但是Component.setEnabled (因为setEnabled不是虚拟的)


所以,因为我创建了一个库,我想远离这些安静的错误

我问:

有没有一个技巧可以避免这个成员函数中的多态性???


谢谢!

解决方案




我不明白为什么你不想让setEnabled成为虚拟...?如果你想要能够通过基类引用调用正确的setEnabled,那么

那么它就是虚拟的!这就是虚函数的全部目的。

它必须是这样或那样的:要么该函数覆盖虚拟的

基类函数,你可以然后通过基础

类指针或引用调用正确的版本,否则该函数隐藏基类

函数,你必须有一个指针或引用实际的

派生类,以便调用派生类的''功能。


-Howard


blockquote>




我明白英语不是你的第一语言,但你的

问题仍然很混乱。如果你不想使用虚函数,你肯定会避免多态性。你想要的不清楚。





任何"特技"无论如何,你提出的可能只需要做一个虚拟的

查询。所以,你通过避免虚拟而获得的收益并不高。除了

使您的代码更难理解。


I have class:
------------
class Component {
void setEnabled(bool state);
}
------------
I want "setEnabled" don''t be virtual (there are many member functions. not virtual for efficient).
If a derived class "Button" does polymorhism in "setEnabled" then in this function:
------------
void func(Component &a) {
a.setEnabled(true);
}
------------
will not be called "Button.setEnabled" but "Component.setEnabled" (because "setEnabled" is not virtual)

So, Because I create a library and I want to be far from these quiet errors
I ask:
Is there a trick to avoid polymorphism in this member function???

Thanks!

解决方案



I don''t understand why you do not want setEnabled to be virtual...? If you
want to be able to call the correct setEnabled via a base class reference,
then it HAS to be virtual! That''s the whole purpose of a virtual function.
It has to be one way or the other: either the function overrides a virtual
base class function and you can then call the correct version via a base
class pointer or reference, or else the function hides the base class
function and you have to have an a pointer or reference to the actual
derived class in order to call the derived class'' function.

-Howard




I understand that English is not your first language, but still your
question is very confusing. You are certainly avoiding polymorphism if you
don''t use virtual functions. What you want is not clear.




Any "trick" you come up with is likely to take as long as doing a virtual
lookup anyway. So, you aren''t gaining much by avoiding "virtual" except
making your code harder to understand.


这篇关于避免多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-20 20:58