您可以在c ++中隐藏虚拟方法吗? [英] Can you Hide a virtual method in c++?

查看:49
本文介绍了您可以在c ++中隐藏虚拟方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有虚函数的基类.

I have a base class with a virtual function.

virtual CString& Foo();

我想像这样在子类中重载

I want to overload this in subclass like so

CString Foo();

有没有办法隐藏基类的虚函数?类似于vb.net或C#

is there a way to hide the base classes virtual function? Something like the new keyword in vb.net or C#

推荐答案

为什么有人会那样做?它违反了基层合同.如果您不想实现与基类具有相同接口的子类,为什么还要继承呢?使用合成.

Why anyone would do something like that? It breaks base class contract. If you don't want to implement subclass that has the same interface as base class, why do you inherit at all? Use composition.

在C ++中没有等效的C# new 关键字.因此,您无法取消方法的虚拟性".

There is no equivalent of C# new keyword in C++. So you cannot cancel method's 'virtualness'.

如果您真的想要这样做,您可以随时:

If you really want to do this you can always:

  • 以私有方式重写子类中的方法.

  • override a method in subclass as private.

创建重载.但是重载必须具有不同的参数.

create overload. But the overload has to have different parameters.

但是,如果这样做,恕我直言,您的设计有问题.我希望每个C ++编译器至少都将这两种情况作为警告.

But if you do this, IMHO something is wrong with your design. I wish each C++ compiler caught both of this situations at least as warnings.

这篇关于您可以在c ++中隐藏虚拟方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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