C++ 中的功能過載和 const 關鍵字


在 C++ 中,我們可以過載函式。有些函式是普通函式;有些是常量型別函式。讓我們看一個程式及其輸出,以瞭解關於常量函式和普通函式的想法。

示例

#include <iostream>
using namespace std;
class my_class {
   public:
      void my_func() const {
         cout << "Calling the constant function" << endl;
      }
      void my_func() {
         cout << "Calling the normal function" << endl;
      }
};
int main() {
   my_class obj;
   const my_class obj_c;
   obj.my_func();
   obj_c.my_func();
}

輸出

Calling the normal function
Calling the constant function

這裡我們可以看到,當物件為普通物件時,將呼叫普通函式。當物件為常量時,將呼叫常量函式。

如果兩個過載方法包含引數,其中一個引數為普通引數,另一個為常量引數,則這將生成錯誤。

示例

#include <iostream>
using namespace std;
class my_class {
   public:
      void my_func(const int x) {
         cout << "Calling the function with constant x" << endl;
      }
      void my_func(int x){
         cout << "Calling the function with x" << endl;
      }
};
int main() {
   my_class obj;
   obj.my_func(10);
}

輸出

[Error] 'void my_class::my_func(int)' cannot be overloaded
[Error] with 'void my_class::my_func(int)'

但如果引數是引用或指標型別,則不會生成錯誤。

示例

#include <iostream>
using namespace std;
class my_class {
   public:
      void my_func(const int *x) {
         cout << "Calling the function with constant x" << endl;
      }
      void my_func(int *x) {
         cout << "Calling the function with x" << endl;
      }
};
int main() {
   my_class obj;
   int x = 10;
   obj.my_func(&x);
}

輸出

Calling the function with x

更新日期:2019-07-30

452 人瀏覽

開啟您的 職業生涯

完成本課程後即可獲得證書

開始
廣告
© . All rights reserved.