#1952. 类与对象-课堂案例3

类与对象-课堂案例3

题目描述

《时钟类》

【时钟类】【友元函数/全局函数方式重载 - 运算符】 要求:使用 class 定义一个 Clock 类。 成员变量包括:小时(hour)、分钟(minute)、秒(second)。 重载减法-运算符实现两个 Clock 对象相减得到相差的秒数。 #include using namespace std; class Clock { private: int hour; int minute; int second; public: // 构造函数 Clock(int h, int m, int s){ hour = h; minute = m; second = s; } // 声明为友元函数(使可以访问类的私有成员) friend int operator-(Clock& t1,Clock& t2); }; // 重载 - 运算符(全局函数)功能:t1-t2得相差的秒数 int operator-(Clock& t1,Clock& t2) { int thisSeconds = t1.hour6060 + t1.minute60 + t1.second; int otherSeconds = t2.hour6060 + t2.minute60 + t2.second; return thisSeconds-otherSeconds; } int main() { Clock c1(23,58,59); Clock c2(23,58,00); cout << c2-c1 << endl; return 0; }

输入格式

无

输出格式

(见样例)