自从我学习C++以来,我甚至想要防止隐藏基类非虚函数一段时间,我不确定这是否符合道德规范,但C++ 11的功能给了我一个想法.假设我有以下内容:
bases.h ....
#ifndef baseexample_h
#define baseexample_h
#include <iostream>
class Base{
public:
void foo() {
std::cout << "Base.foo()\n" << std::endl;
}
};
class Derived: public Base{
public:
void foo(){
std::cout << "Derived.foo()\n" << std::endl;
}
};
#endif
Run Code Online (Sandbox Code Playgroud)
和main.cpp ...
#include "bases.h"
#include <iostream>
int main()
{
Base base;
Derived derived;
base.foo();
derived.foo();
std::cin.get();
return 0;
};
Run Code Online (Sandbox Code Playgroud)
当然是输出
Base.foo()
Derived.foo()
Run Code Online (Sandbox Code Playgroud)
因为派生的foo()函数隐藏了基本的foo函数.我想防止可能的隐藏,所以我的想法是将头文件基本定义更改为:
//.....
class Base{
public:
virtual void foo() final {
std::cout << "Base.foo()\n" << std::endl;
}
};
class …
Run Code Online (Sandbox Code Playgroud)