运算符重载函数的处理方式有两种:类成员函数,友元函数
形参个数 |
成员函数 |
友元函数 |
单目运算符 |
0个 |
1个 |
双目运算符 |
1个 |
2个 |
函数格式:
函数类型 operator 运算符名称(形参表){对运算符的重载处理}
单目运算符
-(负号)的重载
成员函数重载
class Coordinate{
public:
Coordinate(int x,int y){m_iX=x;m_iY=y;};
Coordinate& operator-();
private:
int m_iX;
int m_iY;
};
Coordinate& Coordinate::operator-(){
m_iX=-m_iX;
m_iY=-m_iY;
}
int main(){
Coordinate coor1(3,5);
-coor1;
return 0;
}
友元函数重载
class Coordinate{
friend Coordinate& operator-(Coordinate &coor);
public:
Coordinate(int x,int y){m_iX=x;m_iY=y;};
private:
int m_iX;
int m_iY;
};
Coordinate& Coordinate::operator-(Coordinate &coor){
coor.m_iX=-coor.m_iX
coor.m_iY=-coor.m_iY
return *this
}
int main(){
Coordinate coor1(3,5);
-coor1;
return 0;
}
前置++
class Coordinate{
public:
Coordinate(int x,int y){m_iX=x;m_iY=y;};
Coordinate& operator++();
private:
int m_iX;
int m_iY;
};
Coordinate& Coordinate::operator++(){
m_iX++;
m_iY++;
return *this;
}
int main(){
Coordinate coor1(3,5);
++coor1;
return 0;
}
后置++
class Coordinate{
public:
Coordinate(int x,int y){m_iX=x;m_iY=y;};
Coordinate& operator++(int);
private:
int m_iX;
int m_iY;
};
Coordinate& Coordinate::operator++(){
Coordinate old(*this);
m_iX++;
m_iY++;
return old;
}
int main(){
Coordinate coor1(3,5);
coor1++;
return 0;
}
双目运算符
+号的重载
成员函数重载
class Coordinate{
public:
Coordinate(int x,int y){m_iX=x;m_iY=y;};
Coordinate& operator+(const Coordinate &coor);
private:
int m_iX;
int m_iY;
};
Coordinate& Coordinate::operator+(const Coordinate &coor){
Coordinate temp(0,0);
temp.m_iX=this->m_iX+coor.m_iX;
temp.m_iY=(*this).m_iY+coor.m_iY;
return temp;
}
int main(){
Coordinate coor1(3,5);
Coordinate coor2(1,2);
Coordinate coor3(0,0);
coor3=coor1+coor2;
return 0;
}
友元函数重载
class Coordinate{
friend Coordinate& operator+(const Coordinate &c1,const Coordinate &c2);
public:
Coordinate(int x,int y){m_iX=x;m_iY=y;};
private:
int m_iX;
int m_iY;
};
Coordinate& Coordinate::operator+(const Coordinate &c1,const Coordinate &c2)
{
Coordinate temp(0,0)
temp.m_iX=c1.m_iX+c2.m_iX
temp.m_iY=c1.m_iY+c2.m_iY
return temp
}
int main(){
Coordinate coor1(3,5);
Coordinate coor2(1,2);
Coordinate coor3(0,0);
coor3=coor1+coor2;
return 0;
}