作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
是否有人知道 C++ 中的语言特性或技术可以防止子类覆盖父类中的特定方法?
class Base {
public:
bool someGuaranteedResult() { return true; }
};
class Child : public Base {
public:
bool someGuaranteedResult() { return false; /* Haha I broke things! */ }
};
即使它不是虚拟的,这仍然是允许的(至少在我使用的 Metrowerks 编译器中),你得到的只是一个关于隐藏非虚拟继承函数 X 的编译时警告。
最佳答案
当您可以将 final
说明符用于虚拟方法(由 C++11 引入)时,您可以做到。让我引用my favorite doc site :
When used in a virtual function declaration, final specifies that the function may not be overridden by derived classes.
适应你的例子:
class Base {
public:
virtual bool someGuaranteedResult() final { return true; }
};
class Child : public Base {
public:
bool someGuaranteedResult() { return false; /* Haha I broke things! */ }
};
编译时:
$ g++ test.cc -std=c++11
test.cc:8:10: error: virtual function ‘virtual bool Child::someGuaranteedResult()’
test.cc:3:18: error: overriding final function ‘virtual bool Base::someGuaranteedResult()’
当您使用 Microsoft 编译器时,还请查看 sealed
关键字。
关于c++ - 有没有办法防止方法在子类中被覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17483/
我是一名优秀的程序员,十分优秀!