cpp 专题
专题目录
您的位置:cpp > cpp 专题 > C++重载
C++重载
作者:--    发布时间:2019-11-20

如果创建两个或多个成员(函数)具有相同的名称,但参数的数量或类型不同,则称为c++重载。 在c++中,我们可以重载:

  • 方法
  • 构造函数
  • 索引属性

这是因为这些成员只有参数。

c++中的重载类型有:

  • 函数重载
  • 运算符重载

c++函数重载

在c++中,具有两个或更多个具有相同名称但参数不同的函数称为函数重载

函数重载的优点是它增加了程序的可读性,不需要为同一个函数操作功能使用不同的名称。

c++函数重载示例

下面来看看看函数重载的简单例子,修改了add()方法的参数数量。

#include <iostream>  
using namespace std;  
class cal {  
    public:  
static int add(int a,int b){    
        return a + b;    
    }    
static int add(int a, int b, int c)    
    {    
        return a + b + c;    
    }    
};   
int main(void) {  
    cal c;  
    cout<<c.add(10, 20)<<endl;    
    cout<<c.add(12, 20, 23);   
   return 0;  
}

执行上面代码,得到以下结果 -

30
55

c++操作符重载

操作符重载用于重载或重新定义c++中可用的大多数操作符。 它用于对用户定义数据类型执行操作。

运算符重载的优点是对同一操作数执行不同的操作。

c++操作符重载示例

下面来看看看在c++中运算符重载的简单例子。 在本示例中,定义了void operator ++ ()运算符函数(在test类内部)。

#include <iostream>  
using namespace std;  
class test  
{  
   private:  
      int num;  
   public:  
       test(): num(8){}  
       void operator ++()   
       {   
          num = num+2;   
       }  
       void print() {   
           cout<<"the count is: "<<num;   
       }  
};  
int main()  
{  
    test tt;  
    ++tt;  // calling of a function "void operator ++()"  
    tt.print();  
    return 0;  
}

执行上面代码,得到以下结果 -

the count is: 10

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册