有没有办法防止一个方法在子类中重写? [英] Is there a way to prevent a method from being overridden in subclasses?

查看:130
本文介绍了有没有办法防止一个方法在子类中重写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道C ++中的一个语言特性或技术,以防止子类在父类中使用特定的方法?

Is anyone aware of a language feature or technique in C++ to prevent a child class from over riding a particular method in the parent class?

class Base {
public:
    bool someGuaranteedResult() { return true; }
};

class Child : public Base {
public:
    bool someGuaranteedResult() { return false; /* Haha I broke things! */ }
};

即使它不是虚拟的,这仍然是允许的(至少在Metrowerks编译器中我使用),你得到的是关于隐藏非虚拟继承函数X的编译时间警告。

Even though it's not virtual, this is still allowed (at least in the Metrowerks compiler I'm using), all you get is a compile time warning about hiding non-virtual inherited function X.

推荐答案

/ p>

A couple of ideas:


  1. 将您的函数设为私有。

  2. 这实际上不会阻止函数被另一个定义覆盖。

除此之外,我不知道语言特性,将锁定您的函数,以防止它被重载,仍然能够通过指向/引用子类调用。

Other than that, I'm not aware of a language feature that will lock away your function in such a way which prevents it from being overloaded and still able to be invoked through a pointer/reference to the child class.

好运气!

这篇关于有没有办法防止一个方法在子类中重写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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