gpt4 book ai didi

c++ - 有没有办法防止方法在子类中被覆盖?

转载 作者:IT老高 更新时间:2023-10-28 12:50:06 24 4
gpt4 key购买 nike

是否有人知道 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com