运算符重载是C++的重要组成部分,它可以让程序更加的简单易懂,简单的运算符使用可以使复杂函数的理解更直观。c++对自定类的算术运算部分保留给了程序员,这也是符合c++灵活特性的。
在c++中要想实现这样的运算就必须自定义运算符重载函数,让它来完整具体工作。
在这里要提醒在这里要提醒读者的是,自定义类的运算符重载函数也是函数,你重载的一切运算符不会因为是你自己定义的就改变其运算的优先级,自定义运算符的运算优先级同样遵循与内部运算符一样的顺序。
除此之外,c++也规定了一些运算符不能够自定义重载,例如.、::、.*、.->、?:。
下面我们来学习如何重载运算符,运算符重载函数的形式是:
返回类型 operator 运算符符号 (参数说明)
{
//函数体的内部实现
}
运算符重载函数的使用主要分为两种形式,一种是作为类的友元函数进行使用,另一种则是作为类的成员函数进行使用。
作为类的成员函数:
#include<iostream>
using namespace std;
class Test{
public:
Test(int b=0){
a = b ;
}
Test operator +(Test& temp){
Test res ;
res.a = this->a + temp.a ;
return res ;
}
//++i
Test& operator ++(){
this->a++ ;
return *this ;
}
//i++
Test operator ++(int){
Test ret(this->a) ;
++(*this) ;
return ret ;
}
public:
int a ;
};
int main(){
Test aa(100) ;
Test c=aa+aa ;
cout<<c.a<<endl ; // 200
c = aa++ ;
cout<<c.a<<endl ; // 100
c = ++aa ;
cout<<c.a<<endl; // 102
system("pause");
return 0;
}
作为类的友元函数:
#include<iostream>
using namespace std;
class Test{
public:
Test(int b=0){
a = b ;
}
friend Test operator +(Test& , Test&) ;
//++i
friend Test& operator ++(Test&) ;
//i++
friend Test& operator ++(Test&,int) ;
public:
int a ;
};
Test operator +(Test& temp1,Test& temp2){
Test res ;
res.a = temp2.a + temp1.a ;
return res;
}
Test& operator ++(Test& temp){
temp.a ++ ;
return temp ;
}
Test& operator ++(Test& temp, int){
Test ret(temp.a) ;
temp.a ++ ;
return ret ;
}
int main(){
Test aa(100) ;
Test c=aa+aa ;
cout<<c.a<<endl ;
c = aa++ ;
cout<<c.a<<endl ;
c = ++aa ;
cout<<c.a<<endl;
system("pause");
return 0;
}