在 C++ 中隐藏基类中的所有重载方法
c++server side programmingprogramming更新于 2025/4/23 14:07:17
在 C++ 中,我们可以使用函数重载技术。但是,如果某个基类有一个重载形式的方法(具有相同名称的不同函数签名),并且派生类重新定义了基类中存在的函数之一,那么该函数的所有重载版本都将对派生类隐藏。
让我们看一个例子来明确这个想法。
示例
#include <iostream> using namespace std; class MyBaseClass { public: void my_function() { cout << "This is my_function. This is taking no arguments" << endl; } void my_function(int x) { cout << "This is my_function. This is taking one argument x" << endl; } }; class MyDerivedClass : public MyBaseClass { public: void my_function() { cout << "This is my_function. From derived class, This is taking no arguments" << endl; } }; main() { MyDerivedClass ob; ob.my_function(10); }
输出
[Error] no matching function for call to 'MyDerivedClass::my_function(int)' [Note] candidate is: [Note] void MyDerivedClass::my_function() [Note] candidate expects 0 arguments, 1 provided