C++ 学生生日差值计算(运算符重载)


一、题目描述

定义一个学生类Student,包含该学生的姓名、出生年、月、日 ,重定义 “-”号实现两个学生之间相差多少天的比较。并利用重载的“-”运算符,求所有学生中年龄相差最大的两个人的名字以及相差天数。


二、输入与输出

1.输入

第一行:输入所需要输入的学生个数;
第二行开始,依次输入每个学生的姓名、出生年、月、日。

3
Tom 1995 1 1
Joe 1995 2 28
Jimmy 1996 1 8

2.输出

输出年龄相差最大的两个人的名字以及相差天数。(输出时两个人的先后顺序跟输入时的先后顺序保持一致)

Tom和Jimmy年龄相差最大,为372天。

三、参考代码

#include<iostream>
#include<cstring>
#include<vector>
using namespace std;

class Date {
	int y, m, d;
public:
	Date() { cin >> y >> m >> d; }

	Date operator++() {
		int days[] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
		if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0))
			days[1]++;
		d++;

		if (d > days[m - 1]) {
			d = 1;
			m++;
		}

		if (m > 12) {
			m = 1;
			y++;
		}

		return *this;
	}

	bool operator<(const Date& a) {
		if (y != a.y)
			return y < a.y;
		if (m != a.m)
			return m < a.m;
		if (d != a.d)
			return d < a.d;
	}

	bool operator==(const Date& a) {
		if (y != a.y)
			return false;
		if (m != a.m)
			return false;
		if (d != a.d)
			return false;
		return 1;
	}

	bool operator!=(const Date& a) {
		if (y != a.y)
			return 1;
		if (m != a.m)
			return 1;
		if (d != a.d)
			return 1;
		return 0;
	}

	int operator - (const Date& a) {
		int cnt = 0;
		Date a1 = *this;
		Date a2 = a;
		if (a2 < a1)
			swap(a1, a2);
		while (a1 != a2) {
			++a1; 
            cnt++;
		}

		return cnt;
	}

};

class Student {
	string name;
	Date birthday;
public:
	Student(string n, Date b) :name(n), birthday(b) {

	}

	friend int operator-(Student& a, Student& b) {
		return a.birthday - b.birthday;
	}

	string getName() {
		return name;
	}

};

int main() {
	int n;
	cin >> n;
	vector<Student>v;
	for (int i = 0; i < n; i++) {
		string name;
		cin >> name;
		Date birthday;
		Student s(name, birthday);
		v.push_back(s);
	}

	int s1, s2;
	int cnt = -1;
	for (int i = 0; i < n - 1; i++)
		for (int j = i + 1; j < n; j++) {
			if (cnt < v[i] - v[j]) {
				cnt = v[i] - v[j];
				s1 = i; s2 = j;
			}
		}

	cout << v[s1].getName() << "和" << v[s2].getName() << "年龄相差最大,为" << cnt << "天。" << endl;

}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Z1Jxxx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值