运算符重载的本质是函数重载。
格式:
返值类型 operator 运算符名称(形参表列) {
重载实体;
}
operator 运算符名称 在一起构成了新的函数名。
4.1 友元重载
class A{
public:
A(int _aa):aa(_aa){};
inline void print(){
cout << aa << endl;
}
friend const A operator+(const A &a1, const A &a2);
private:
int aa;
};
//全局友元操作符重载
const A operator+(const A &a1, const A &a2){
return A(a1.aa+a2.aa);
}
int main(){
A a1(1);
A a2(2);
A a3 = operator+(a1, a2);//显示调用
// A a3 = a1+ a2;//隐式调用
a3.print();
return 0;
}
4.2 成员重载
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(float x=0, float y=0)
:_x(x),_y(y){}
void dis()
{
cout<<"("<<_x<<","<<_y<<")"<<endl;
}
friend const Complex operator+(const Complex &c1,const Complex &c2);
const Complex operator+(const Complex &another);
private:
float _x;
float _y;
};
const Complex operator+(const Complex &c1,const Complex &c2)
{
cout<<"友元函数重载"<<endl;
return Complex(c1._x + c2._x,c1._y + c2._y);
}
const Complex Complex::operator+(const Complex & another)
{
cout<<"成员函数重载"<<endl;
return Complex(this->_x + another._x,this->_y + another._y);
}
int main()
{
Complex c1(2,3);
Complex c2(3,4);
c1.dis();
c2.dis();
//