/* * Copyright (c) leo * All rights reserved. * filename: f0805.cpp * summary : 重载操作符 * version : 1.0 * author : leo * date : 6.16.2011 */ #include<iostream> #include<iomanip> using namespace std; class Point { int x, y; public: void set(int a, int b); void print()const; friend Point operator+(const Point &a, const Point &b); //普通函数 Point operator+(const Point &d); //成员函数 friend Point add(const Point &a, const Point &b); friend ostream& operator<<(ostream &o, const Point &d); //不能作成员函数,为访问似有成员加friend }; inline void Point::set(int a, int b) { x = a; y = b; } inline void Point::print()const { cout<<"("<<x<<", "<<y<<")"<<endl; } ostream& operator<<(ostream &o, const Point &d) { return o<<"("<<d.x<<", "<<d.y<<")"<<endl; } Point operator+(const Point &a, const Point &b)//如果是成员函数,则参数个数过多 { Point s; s.set(a.x+b.x, a.y+b.y); return s; //返回值,而不能返回引用,因为s是临时量,生命随表达式的结束而结束 } inline Point Point::operator+(const Point &d) //成员函数,作为二目操作符其参数个数只能为1 { Point s; s.set(x+d.x, y+d.y); return s; } Point add(const Point &a, const Point &b) //普通函数,也可以设计为成员函数 { Point s; s.set(a.x+b.x, a.y+b.y); return s; } int main() { Point a,b,c ; a.set(3,2); b.set(1,5); (a+b).print(); a.operator +(b).print(); add(a,b).print(); cout<<(a+b)<<endl; return 0; } /* * Copyright (c) leo * All rights reserved. * filename: f0806.cpp * summary : Time类的operator++重载 * version : 1.0 * author : leo * date : 6.17.2011 */ #include<iostream> #include<iomanip> using namespace std; class Time { int hour, minute, second; public: void set(int h, int m, int s); friend Time& operator++(Time &a); //前自增 friend Time operator++(Time &a, int);//后自增 friend ostream& operator<<(ostream &o, const Time &t); }; inline void Time::set(int h, int m, int s) { hour = h; minute = m; second = s; } Time & operator++(Time &a) //前增量,返回对象的引用 { if(!(a.second = (a.second+1)%60) && !(a.minute = (a.minute+1)%60)) a.hour = (a.hour+1)%24; return a; } Time operator++(Time &a, int) //后增量,返回临时对象 { Time t(a); //t 与 a不是同一个实体,t是对a的拷贝 if(!(a.second = (a.second+1)%60) && !(a.minute = (a.minute+1)%60)) a.hour = (a.hour+1)%24;//原参数对象发生了变化 return t; //返回一个临时对象,是参数对象变化以前的值 } ostream & operator<<(ostream &o, const Time &t)//重载输出流 { o<<setfill('0')<<setw(2)<<t.hour<<":"<<setw(2)<<t.minute<<":"<< setw(2)<<t.second<<"/n"<<setfill(' '); return o; } int main() { Time t; t.set(11, 59, 58); cout<<t++; //11:59:58 cout<<endl<<++t; //12:00:00 return 0; }