对象相加函数模板

目录

题目描述

AC代码


时间限制1s

内存限制128MB

难度1

题目描述

时钟类CClock有时、分、秒;人民币类CRmb有元、角、分三个数据成员。试为这种类型的类对象定义一个两两相加的函数模板add,包括三个参数:2个对象和一个int表示进制。(要求不能用函数重载的方法)

主函数如下所示:

...

CClock c1(...), c2(...), c;

c = add(c1, c2, 60);

cout << c << endl;

CRmb r1(...), r2(...), r;

r = add(r1, r2, 10);

cout << r << endl;

输入

第一个时钟对象的时分秒

第二个时钟对象的时分秒

第一个人民币对象的元角分

第二个人民币对象的元角分

输出

两个时钟对象相加的结果

两个人民币对象相加的结果

输入样例1

15 34 25
7 25 36
5 6 7
3 4 5

输出样例1

23 0 1
9 1 2

AC代码

#include<iostream>
using namespace std;
class CClock {
		int hour, minute, second;
	public:
		CClock(){}
		CClock(int h, int m, int s): hour(h), minute(m), second(s) {}
		int gethour() {
			return hour;
		}
		int getminute() {
			return minute;
		}
		int getsecond() {
			return second;
		}
		CClock operator+(CClock& another) {
			int a=hour + another.gethour(),b=minute + another.getminute(),c=second + another.getsecond();
			if(c>59)
			{
				c=c%10;
				b++;
			}
			if(b>59)
			{
				b=b%10;
				a++;
			}		
			if(a>23)
			a=a%24;	
			CClock temp(a, b,c );
			return temp;
		}
		friend ostream& operator<<(ostream&out, CClock & temp);
};
class CRmb {
		int yuan, jiao, fen;
	public:
		CRmb(){}
		CRmb(int y, int j, int f): yuan(y), jiao(j), fen(f) {}
		int getyuan() {
			return yuan;
		}
		int getjiao() {
			return jiao;
		}
		int getfen() {
			return fen;
		}
		CRmb operator+(CRmb& another) {
			int a=yuan + another.getyuan(),b=jiao +another.getjiao(),c=fen + another.getfen();
			if(c>9)
			{
				c=c%10;
				b++;
			}
			if(b>9)
			{
				b=b%10;
				a++;
			}
			CRmb temp(a,b  ,c );
			return temp;
		}
		friend ostream& operator<<(ostream&out, CRmb & temp);
};
ostream& operator<<(ostream&out, CClock & temp){
	out<<temp.hour<<' '<<temp.minute<<' '<<temp.second;
	return out;
}
ostream& operator<<(ostream&out, CRmb & temp){
	cout<<temp.yuan<<' '<<temp.jiao<<' '<<temp.fen;
	return out;
}
template<class T>
T add(T& a, T& b, int n) {
	T temp = a + b;
	return temp;
}
int main() {
	int a,b,cc,d,e,f;
	cin>>a>>b>>cc>>d>>e>>f;
	CClock c1(a,b,cc), c2(d,e,f), c;
	c = add(c1, c2, 60);
	cout << c << endl;
	cin>>a>>b>>cc>>d>>e>>f;
	CRmb r1(a,b,cc), r2(d,e,f), r;
	r = add(r1, r2, 10);
	cout << r << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_62264287/article/details/125321098