现在的位置: 首页 > 综合 > 正文

c++重载操作符使用示例

2013年08月28日 ⁄ 综合 ⁄ 共 1990字 ⁄ 字号 评论关闭

1.overload.h代码如下:

#ifndef OVERLOAD_H_

#define OVERLOAD_H_
#include <iostream>
class OverLoad{
private:
    double x;
    double y;
public:
    OverLoad(){};
    OverLoad(double x,double y);
    OverLoad& operator=(const OverLoad &a);
    OverLoad& operator+=(const OverLoad &a);
    OverLoad& operator-=(const OverLoad &a);
    OverLoad& operator++();
    OverLoad& operator--();
    double getX(){
        return this->x;
    }
    double getY(){
        return this->y;
    }
public:
    friend OverLoad operator+(const OverLoad &a,const OverLoad &b);
    friend OverLoad operator-(const OverLoad &a,const OverLoad &b);
    friend std::istream& operator>>(std::istream& in, OverLoad &p);
    friend std::ostream& operator<<(std::ostream& os, const OverLoad &p);

};

#endif /* OVERLOAD_H_ */

2.overload.cpp代码如下:

#include "overload.h"
OverLoad::OverLoad(double x,double y){
    this->x = x;
    this->y = y;
}
OverLoad operator+(const OverLoad &a,const OverLoad &b){
    return OverLoad(a.x+b.x,a.y+b.y);
}
OverLoad operator-(const OverLoad &a,const OverLoad &b){
    return OverLoad(a.x-b.x,a.y-b.y);
}
OverLoad& OverLoad::operator=(const OverLoad &a){
    this->x = a.x;
    this->y = a.y;
    return *this;
}
OverLoad& OverLoad::operator+=(const OverLoad &a){
    this->x = this->x + a.x;
    this->y = this->y + a.y;
    return *this;
}
OverLoad& OverLoad::operator-=(const OverLoad &a){
    this->x = this->x - a.x;
    this->y = this->y - a.y;
    return *this;
}
OverLoad& OverLoad::operator++(){
    this->x++;
    this->y++;
    return *this;
}
OverLoad& OverLoad::operator--(){
    this->x--;
    this->y--;
    return *this;
}
std::istream& operator>>(std::istream& in, OverLoad& p)
{
    in>>p.x>>p.y;
    return in;
}
std::ostream& operator<<(std::ostream& os, const OverLoad &p)
{
    os<<p.x<<" "<<p.y;
    return os;
}

3.main.cpp代码如下:

#include "overload.h"
using std::cin;
using std::cout;
using std::endl;
int main()
{
    OverLoad a(2,9);
    OverLoad b(10,5);
    OverLoad c(1,1);
    OverLoad temp;
    temp = a + b;
    temp += c;
    temp -= a;
    cout<<temp.getX()<<" "<<temp.getY()<<endl;
    cout<<a<<" "<<b<<endl;
    return 0;
}

PS:初写文章,文笔生涩之处,各位请见谅,若有疑问或者交流的,可加本人YY号:301558660

转载请注明出处:山水间博客,http://blog.csdn.net/linyanwen99/article/details/7797579

抱歉!评论已关闭.