c++ 重载运算符

重载+或-运算符

重载方式有两种,一种是全局函数的方式,另外一种是成员函数的方式。

全局函数

class MyClass
{

    
public:
    int x;
    int y;

    MyClass(int x,int y);

    ~MyClass();void print()
    {
        cout << "x = " << x<< "\ty = " << y << endl;
    }
};
MyClass operator+(MyClass &c1, MyClass &c2)
{
    MyClass res(c1.x + c2.x, c1.y + c2.y);
    return res;
}

MyClass::MyClass(int x,int y)
{
    this->x =x;
    this->y = y;

}

MyClass::~MyClass()
{


}
int _tmain(int argc, _TCHAR* argv[])
{
    
    MyClass c1(2,3);
    MyClass c2(4,5);
    MyClass c3 = c1+c2;
    
    c3.print();
     return 0;

}

 

 

成员函数的方式

class MyClass
{

    
public:
    int x;
    int y;

    MyClass(int x,int y);

    ~MyClass();

     MyClass& operator+( MyClass &c1); //成员函数的声明
    void print()
    {
        cout << "x = " << x<< "\ty = " << y << endl;
    }
};


MyClass& MyClass::operator+( MyClass &c1) //实现需要加 域::   此处隐藏指向对象的this指针
{
    MyClass res(c1.x + this->x, c1.y + this->y);
    return res;
}


MyClass::MyClass(int x,int y)
{
    this->x =x;
    this->y = y;

}

MyClass::~MyClass()
{


}int _tmain(int argc, _TCHAR* argv[])
{
    
    MyClass c1(2,3);
    MyClass c2(4,5);
    MyClass c3 = c1+c2;
    
    c3.print();
     return 0;
}

 

 

 

重载++或者- -

分为前置++和后置++

同样两种方法,全局或者成员函数的方式

全局方式   注释为成员函数方式,隐藏this指针

class MyClass
{

    
public:
    int x;
    int y;

    MyClass(int x,int y);

    ~MyClass();

//MyClass& operator++(); 成员函数方式
void print() { cout << "x = " << x<< "\ty = " << y << endl; } };
MyClass::MyClass(
int x,int y) { this->x =x; this->y = y; } MyClass::~MyClass() { } MyClass& operator ++(MyClass &c1)//前置++ { c1.x++; c1.y++; return c1; }

/*

MyClass& MyClass::operator ++()//前置++  成员函数的方式
{
this->x++;
this->y++;
return *this;
}

*/
int _tmain(int argc, _TCHAR* argv[]) { MyClass c1(2,3); ++c1; c1.print(); return 0; }

 

 

 

后置++需要在函数中加int 防止与前置++重复

class MyClass
{

    
public:
    int x;
    int y;

    MyClass(int x,int y);

    ~MyClass();

    MyClass& operator++(int);

    void print()
    {
        cout << "x = " << x<< "\ty = " << y << endl;
    }
};



MyClass::MyClass(int x,int y)
{
    this->x =x;
    this->y = y;
}

MyClass::~MyClass()
{
}


MyClass& MyClass::operator ++(int)//后置++
{
    this->x++;
    this->y++;
    return *this;
}

/*
MyClass& operator ++( MyClass c1,int)//后置++ 全局函数方式
{
    c1.x++;
    c1.y++;
    return c1;
}
*/

int _tmain(int argc, _TCHAR* argv[])
{
    
    MyClass c1(2,3);
    c1++;
    c1.print();
    return 0;

}

 

 - -的重载和++同理

 

参考博客:https://www.cnblogs.com/qq209049127/p/10542475.html

posted @ 2020-06-15 12:28  海拉尔  阅读(162)  评论(0编辑  收藏  举报