有没有办法防止一个方法在子类中重写? [英] Is there a way to prevent a method from being overridden in subclasses?
问题描述
有没有人知道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:
- 将您的函数设为私有。
- 这实际上不会阻止函数被另一个定义覆盖。
除此之外,我不知道语言特性,将锁定您的函数,以防止它被重载,仍然能够通过指向/引用子类调用。
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屋!