1、成员函数重载
2、友元函数重载
一元运算符
1、负号重载(友元函数方式)
#include <iostream>
using namespace std;
class Coordinate{
friend Coordinate& operator-(Coordinate&coordinate);
public:
void show(){
cout<<x<<" "<<y<<endl;
}
private:
int x=1;
int y=1;
};
Coordinate& operator-(Coordinate& coordinate){
coordinate.x = -coordinate.x;
coordinate.y = -coordinate.y;
return coordinate;
}
int main(){
Coordinate c;
c.show();
c = -c;
c.show();
}
2、自增重载(成员函数方式)
#include <iostream>
using namespace std;
class Coordinate{
public:
Coordinate& operator++(){//++x
x++;
y++;
return *this;
}
Coordinate operator++(int){//x++
Coordinate old(*this);
x++;
y++;
return old;
}
void show(){
cout<<x<<" "<<y<<endl;
}
private:
int x=1;
int y=1;
};
int main(){
Coordinate c;
c.show();
c++;
c.show();
}
二元运算符
1、加法运算符(+)
#include <iostream>
using namespace std;
class Coordinate{
public:
Coordinate operator+(const Coordinate& coordinate){
Coordinate temp;
temp.x = x+coordinate.x;
temp.y = y+coordinate.y;
return temp;
}
void show(){
cout<<x<<" "<<y<<endl;
}
private:
int x=1;
int y=1;
};
int main(){
Coordinate c;
c.show();
c = c+c;
c.show();
}
2、输出运算符(<<,只能通过友元函数重载)
#include <iostream>
using namespace std;
class Coordinate{
friend ostream& operator<<(ostream& out,const Coordinate& coordinate);
private:
int x=1;
int y=1;
};
ostream& operator<<(ostream& out,const Coordinate& coordinate){
out<<coordinate.x<<","<<coordinate.y;
return out;
}
int main(){
Coordinate c;
cout<<c;
}
3、索引运算符([],只能通过成员函数重载)
#include <iostream>
using namespace std;
class Coordinate{
public:
int operator[](int index){
if(0 == index)
return x;
if(1 == index)
return y;
return -1;
}
private:
int x=1;
int y=1;
};
int main(){
Coordinate c;
cout<<c[0]<<","<<c[1]<<endl;
}