C++ 中隱藏基類中的全部過載方法


在 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

更新於: 2019-07-30

468 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.