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

查看:28
本文介绍了用 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.

我在一些代码中看到过这个习语,我相信作者试图使类成为最终的,这是基于不可能覆盖私有成员函数的假设.但是,本文展示了一个覆盖私有函数的示例.当然另一部分C++ faq推荐反对这样做.

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. 在派生类和基类中对虚拟方法使用不同的权限是否有任何技术问题?

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

这样做有什么正当理由吗?

Is there any legitimate reason to do so?

推荐答案

问题在于 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."

在派生类中,当您将 Base 声明为公有私有的内容进行更改时,您将带走一些内容.现在,即使派生对象是"基对象,您应该能够对基类对象执行的操作对派生类对象无法执行,从而打破了 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,但您不能像对矩形那样独立于其高度更改 Square 的宽度)并且您可能需要重新考虑您的类关系.

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天全站免登陆