如何在派生类调用基类的同名方法
需求
C++派生类希望覆盖基类同名方法,但不使用虚函数直接覆盖。
实现
通过namespace区别基类方法的调用。在线试验
https://godbolt.org/z/McKqaoP3r
#include <iostream>
class base
{
public:
void show()
{
std::cout << "This is base speaking." << std::endl;
}
};
class other: public base
{
public:
void show()
{
base::show();
std::cout << "This is other speaking." << std::endl;
}
};
int main()
{
other o;
o.show();
return 0;
}
结果
ASM generation compiler returned: 0
Execution build compiler returned: 0
Program returned: 0
This is base speaking.
This is other speaking.