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.