用C ++中的私有函数覆盖公共虚拟函数 [英] Overriding public virtual functions with private functions in C++

查看:165
本文介绍了用C ++中的私有函数覆盖公共虚拟函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有任何理由使覆盖的C ++虚函数的权限不同于基类吗?这样做是否有危险?

Is there is any reason to make the permissions on an overridden C++ virtual function different from the base class? Is there any danger in doing so?

例如:

class base {
    public:
        virtual int foo(double) = 0;
}

class child : public base {
    private:
        virtual int foo(double);
}

C ++ faq 说这是一个坏主意,但不说为什么。

The C++ faq says that it is a bad idea, but doesn't say why.

我在一些代码中看到了这个习语,我相信作者试图根据一个假设,即不可能覆盖一个私有成员函数来做类的final。但是,本文显示了覆盖私有函数的示例。当然, C ++常见问题的另一部分建议

I have seen this idiom in some code and I believe that the author was attempting to make the class final, based on an assumption that it is not possible to override a private member function. However, This article shows an example of overriding private functions. Of course another part of the C++ faq recommends against doing so.

我的具体问题:


  1. 任何在派生类vs基类中对虚拟方法使用不同权限的技术问题?

  1. Is there any technical problem with using a different permission for virtual methods in derived classes vs base class?

有没有合理的理由?


推荐答案

问题是Base类方法是它声明接口的方法。它实质上是说,这些是你可以对这个类的对象做的事情。

The problem is that the Base class methods are its way of declaring its interface. It is, in essence saying, "These are the things you can do to objects of this class."

当在Derived类中,你做一些基地声明为公共私人,你正在带走的东西。现在,即使一个派生对象is-a基础对象,你应该能够做一个Base类对象,你不能对Derived类对象,打破 Liskov替换原则

When in a Derived class you make something the Base had declared as public private, you are taking something away. Now, even though a Derived object "is-a" Base object, something that you should be able to do to a Base class object you cannot do to a Derived class object, breaking the Liskov Substitution Prinicple

这会在您的计划中造成技术问题吗?也许不会。但是这可能意味着你的类的对象不会以你的用户期望他们的行为的方式表现。

Will this cause a "technical" problem in your program? Maybe not. But it will probably mean object of your classes won't behave in a way your users expect them to behave.

如果你发现自己在这种情况下, (除了在另一个答案中引用的弃用方法的情况下),你有一个继承模型,继承不是真正的建模is-a(例如,Scott Myers的例子Square继承自Rectangle,但你可以不必改变一个正方形的宽度而不管其高度,就像你可以为一个矩形),你可能需要重新考虑你的类关系。

If you find yourself in the situation where this is what you want (except in the case of a deprecated method referred to in another answer), chances are you have an inheritance model where inheritance isn't really modeling "is-a," (e.g. Scott Myers's example Square inheriting from Rectangle, but you can't change a Square's width independent of its height like you can for a rectangle) and you may need to reconsider your class relationships.

这篇关于用C ++中的私有函数覆盖公共虚拟函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆