问题描述
Hello All
我有一个名为Action_Request的基类,以及一组对应于不同种类的Action_Request的类
,每个类都继承。例如: -
class Add_Molecule_Req:public Action_Request {
// ......
};
我使用虚拟函数通过
Action_Requests的公共接口以多态方式操作各种派生类。
目前最重要的功能是派生类(包括
析构函数,它会覆盖Action_Request的虚拟析构函数),
声明公开。
我的程序编译,如果我将它们设为私有,并且这样做似乎
的优点是必须始终调用这些函数
通过Action_Request的公共接口进行多态化,这就是我想要的b $ b。
我的问题是: -
i)覆盖公共虚拟功能私人功能好
练习?
ii)有没有缺点?
Chris Gordon-Smith
www.simsoup.info
Hello All
I have a base class called Action_Request, and a set of classes
corresponding to different kinds of Action_Request, each of which inherits
from Action_Request. Eg:-
class Add_Molecule_Req: public Action_Request{
// ......
};
I manipulate the various derived classes polymorphically through
Action_Requests''s public interface, using its virtual functions.
Currently the overriding functions in the derived classes (including the
destructor, which overrides Action_Request''s virtual destructor), are
declared public.
My program compiles if I make them private, and doing this would seem to
have the advantage that these functions must then always be invoked
polymorphically through Action_Request''s public interface, which is what I
want.
My questions are:-
i) Is overriding public virtual functions with private functions good
practice?
ii) Are there any disadvantages?
Chris Gordon-Smith
www.simsoup.info
推荐答案
我倾向于遵循指南,如果可以,请将其设为私有,公开,如果你必须使用
。我认为这样的代码是良好实践。
唯一的缺点是,某个具有某些
ActionRequest子类的对象将不得不向上 - 投射对象。
I tend to follow the guideline, "make it private if you can, public if
you must." I consider such code "good practice".
The only disadvantage is that someone with a object of some
ActionRequest sub-class will have to up-cast the object.
一般来说,你应该将接口(公共API,基类
提供)与可配置性(覆盖功能)分开。这也是
称为模板方法模式,这里有详细描述:
-
Dizzy
In general you should separate interface (the public API the base class
provides) from configurability (the overriding feature). This is also
called the Template Method Pattern and is described in detail here:
http://www.gotw.ca/publications/mill18.htm
--
Dizzy
我倾向于遵循指南,如果可以,请将其设为私有,公开,如果你必须使用
。我认为这样的代码是良好做法。
I tend to follow the guideline, "make it private if you can, public if
you must." I consider such code "good practice".
对我来说听起来很明智。我没有意识到(因为我没有真正想过它),派生类中的私有方法可以覆盖基础中的公共方法。
Sounds sensible to me. What I hadn''t appreciated (because I hadn''t really
thought about it), is that private methods in derived class can override
public methods in the base.
在我的情况下,这不是一个问题,因为操纵只需要通过基地进行
。如果我尝试通过派生的
类指针进行操作,我将收到编译器错误。上传是可能的,但
将违背我的基本设计原则。
Chris Gordon-Smith
这篇关于使用私有函数覆盖公共虚函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!