如何防止派生类中的方法被重写?
如何强制基类方法不被派生类覆盖?
How can I enforce that a base class method is not being overridden by a derived class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何强制基类方法不被派生类覆盖?
How can I enforce that a base class method is not being overridden by a derived class?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
如果您能够使用
final
说明符C++11 您可以防止派生类重写该方法。 (微软编译器似乎支持类似的sealed
具有类似的语义。)这是一个例子:
这是我尝试编译它时得到的结果:
If you are able to use the
final
specifier from C++11 you can prevent derived classes from override that method. (Microsoft compilers appear to support the similarsealed
with similar semantics.)Here's an example:
Here's what I get when I try to compile it:
如果将该方法设置为非虚拟方法,则派生类无法重写该方法。但是,在 C++03 中,类不能重写基类的方法,并且还可以防止进一步的派生类重写相同的方法。一旦该方法是虚拟的,它就保持虚拟的状态。
If you make the method non-virtual, derived classes cannot override the method. However, in C++03 a class cannot override a method from a base class, and also prevent further derived classes from overriding the same method. Once the method is virtual, it stays virtual.
不要让它变得虚拟。
这不会阻止从您的类派生并隐藏该函数(通过提供另一个同名成员函数)。但是,如果您的类不打算派生(没有虚拟析构函数,没有虚拟成员函数),那么这不应该是问题。
Don't make it virtual.
This won't prevent deriving from your class and hiding the function (by providing another member function with the same name). However, if your class is not meant to be derived anyway (no virtual destructor, no virtual member functions), that shouldn't be an issue.
如果你想保持公开,就不要声明它是虚拟的。
编辑:Srikanth 评论说想知道重写派生类中的私有成员函数。
well if you want to keep it public, dont declare it virtual.
EDIT: Srikanth commented wondering about overriding a private member function in a derived class.