运算符重载(1)

运算符重载函数的处理方式有两种:类成员函数友元函数

形参个数 成员函数 友元函数
单目运算符 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;         //coor1.operator-();
    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;         //operator-(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;            //coor1.operator++();
    return 0;
}

后置++

class Coordinate{
public:
    Coordinate(int x,int y){m_iX=x;m_iY=y;};
    Coordinate& operator++(int);//int仅仅用来区分前置++,没有特别意义
private:
    int m_iX;
    int m_iY;
};
Coordinate& Coordinate::operator++(){
    Coordinate old(*this);//创建对象old保存进行++运算前的对象数据
    m_iX++;
    m_iY++;
    return old;
}
int main(){
    Coordinate coor1(3,5);
    coor1++;            //coor1.operator++(0);
    return 0;
}

双目运算符

+号的重载

成员函数重载

class Coordinate{
public:
    Coordinate(int x,int y){m_iX=x;m_iY=y;};
    Coordinate& operator+(const Coordinate &coor);
    //const防止错误的修改,不写也可以,不影响本例结果
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;          //coor3=coor1.operator+(coor2);
    return 0;
}

友元函数重载

class Coordinate{
    friend Coordinate& operator+(const Coordinate &c1,const Coordinate &c2);
    //const防止错误的修改,不写也可以,不影响本例结果
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;          
    //coor3=operator+(coor1,coor2);
    return 0;
}

你可能感兴趣的:(c++)