C++运算符重载

1、成员函数重载

2、友元函数重载

一元运算符

1、负号重载(友元函数方式)

#include 
using namespace std;
class Coordinate{
    friend Coordinate& operator-(Coordinate&coordinate);
public:
    void show(){
        cout<

2、自增重载(成员函数方式)

#include 
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<

二元运算符

1、加法运算符(+)

#include 
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<

2、输出运算符(<<,只能通过友元函数重载)

#include 
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<

3、索引运算符([],只能通过成员函数重载)

#include 
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++)