- 在 c++11 中,
override
说明符防止不覆盖预期的虚拟基函数(因为签名不匹配)。 - 说明
final
符可防止无意中覆盖派生类中的函数。
=> 是否有一个说明符(类似于 Maybefirst
或no_override
)来防止覆盖未知的基函数?
当一个虚函数被添加到一个与派生类中已经存在的虚函数具有相同签名的基类时,我想得到一个编译器错误。
编辑 4:为了使这个问题简单且答案相关,这里又是
原始伪代码
- 摘要
class B : A
有private: virtual void fooHasBeenDone() = 0;
class C : B
工具private: virtual void fooHasBeenDone() override { react(); }
- 现在
class A
得到一个新的private: virtual void fooHasBeenDone();
- 但新的
A::foo
可能与原来的有所不同B::foo
。
和一个具体的例子
- 摘要
class B : A
有virtual void showPath() = 0;
一个 PainterPath class C : B
工具virtual void showPath() override { mPath.setVisible(); }
- 现在
class A
得到一个新的virtual void showPath();
含义文件路径 - 现在,当 A 调用 showPath() 时,B 显示painterPath 而不是某个文件路径。
当然这是错误的,然后我也应该重命名B::showPath()
并B::showPainterPath()
实现B::showPath() override
。我只是想从编译器那里得到通知。
这是一个编译的真实示例:
#include <iostream>
#define A_WITH_SHOWPATH
class A
{
#ifdef A_WITH_SHOWPATH
public:
void setPath(std::string const &filepath) {
std::cout << "File path set to '" << filepath << "'. Display it:\n";
showPath();
}
// to be called from outside, supposed to display file path
virtual void showPath() {
std::cout << "Displaying not implemented.\n";
}
#else
// has no showPath() function
#endif
};
class B : public A
{
public:
virtual void showPath() = 0; // to be called from outside
};
class C1 : public B {
public:
virtual void showPath() override {
std::cout << "C1 showing painter path as graphic\n";
}
};
class C2 : public B {
public:
virtual void showPath() override {
std::cout << "C2 showing painter path as widget\n";
}
};
int main() {
B* b1 = new C1();
B* b2 = new C2();
std::cout << "Should say 'C1 showing painter path as graphic':\n";
b1->showPath();
std::cout << "---------------------------\n";
std::cout << "Should say 'C2 showing painter path as widget':\n";
b2->showPath();
std::cout << "---------------------------\n";
#ifdef A_WITH_SHOWPATH
std::cout << "Should give compiler warning\n or say \"File path set to 'Test'. Display it:\"\n and \"Displaying not implemented.\",\n but not \"C1 showing painter path as graphic\":\n";
b1->setPath("Test");
std::cout << "# Calling setPath(\"Test\") on a B pointer now also displays the\n# PainterPath, which is not the intended behavior.\n";
std::cout << "# The setPath() function in B should be marked to never override\n# any function from the base class.\n";
std::cout << "---------------------------\n";
#endif
return 0;
}
运行它并查看文本输出。
作为参考,具有特定用例(PainterPath 实例)的旧示例:
https://ideone.com/6q0cPD(链接可能已过期)