C++重载操作符的简单实例

来源:互联网 发布:蓝格美容院软件 编辑:程序博客网 时间:2024/05/16 12:28
 
/* *重载操作符的简单学习实例,参考《C++ Primer》 *重载操作符要求:必须具有一个类类型的操作数, *优先级与结合性是固定的,不在具有短路求值特性**/#include <iostream>using std::cin;using std::cout;using std::endl;class Point{public:Point(int tx = 0, int ty = 0):x(tx), y(ty){};Point& operator++();   //前缀操作Point operator++(int); //后缀操作Point& operator+=(const Point&);//成员函数public: //重载操作符friend std::istream& operator>>(std::istream& in, Point& pt);friend std::ostream& operator<<(std::ostream& os, const Point& pt);friend Point operator+(const Point&, const Point&);private:int x, y;};Point& Point::operator++(){x++, y++;return *this;//返回改变后的值}Point Point::operator++(int){Point tmp(*this);++*this;return tmp;//返回改变前的值}Point& Point::operator+=(const Point& pt){x += pt.x;y += pt.y;return *this;}Point operator+(const Point& a, const Point& b){Point tmp(a);tmp += b;return tmp; //返回使用默认的复制构造函数}std::istream& operator>>(std::istream& in, Point& pt){in>>pt.x>>pt.y;return in;}std::ostream& operator<<(std::ostream& os, const Point& pt){os<<pt.x<<' '<<pt.y;return os;}int main(){Point a(0, 0), b;cin>>b;cout<<b++<<"; "<<++b<<endl;cout<<a+b<<endl;//显式调用格式为 operator+(a, b);a += b; //显式调用格式为 a.operator+=(b);cout<<a<<endl;}/*输入为 1 1 时输出2 2; 3 33 33 3*/