运算符重载(一)

来源:互联网 发布:mac系统照片处理软件 编辑:程序博客网 时间:2024/05/16 17:33
重载为友员函数。
 
#include <iostream>using namespace std;class Clock{private:int s;int m;int h;public:void display();Clock(Clock &);Clock(int, int, int);friend Clock operator+(int, Clock&);friend Clock operator+(Clock&, int);};void Clock::display(){cout << h << ":" << m << ":" << s << endl;}Clock::Clock(Clock&c){m = c.m;s = c.s;h = c.h;}Clock::Clock(int x, int y, int z){h = x;m = y;s = z;}Clock operator +(int x,Clock&c){Clock clk = c;clk.h += c.h;clk.h %= 24;if (clk.h < 0)clk.h += 24;return clk;}Clock operator+(Clock&c, int x){Clock clk = c;clk.h += c.h;clk.h %= 24;if (clk.h < 0)clk.h += 24;return clk;}void main(){Clock one(5, 30, 0);one.display();Clock two = one + 4;two.display();Clock three = 100 + two;three.display();getchar();}


 

0 0
原创粉丝点击