在c++11中,
override
修饰符可以防止不意外地覆盖基类中的虚函数(因为签名不匹配)。final
修饰符可以防止无意中覆盖派生类中的函数。是否有一个修饰符(例如first
或no_override
)可以防止覆盖未知的基函数?我希望在基类中添加具有与派生类中已存在的虚函数相同签名的虚函数时,编译器会报错。以下是一个抽象类B和其子类C的示例,当类A添加了新的虚函数时,B中的showPath()将显示错误的内容。为了避免这种情况,应该重命名B::showPath()并实现B::showPath()的覆盖。#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(链接可能已过期)
B
的实例”这个术语?这会造成困惑,因为B
由于是纯虚函数而不能有实例。另外,PainterPath
在这里有什么作用?你最后的陈述很令人困惑。我建议你不要放置实际的带构造函数等代码,只需放置独立的最小部分,任何人都可以使用ideone.com进行验证。你也可以看一下我的答案和评论,如果它们不能满足你的需求。 - iammilind