【C++】类和对象2

回顾:

什么时候用引用返回,什么时候用传值返回,出了作用域变量还在就用引用返回,除了作用域变量销毁,则用传值返回

1. 日期类的比较大小操作符:(Date.h,函数声明)

写出其中两个,另外的四个都能写出来:
Date.cpp类:

bool Date::operator<(const Date& d)
{
	if (_year < d._year)
	{
		return true;
	}
	else if (_year == d._year) {
		if (_month < d._month)
		{
			return true;
		}
		else if (_month == d._month)
		{
			return _day < d._day;
		}
	}
	return false;
}

bool Date::operator<=(const Date& d)
{
	return *this < d || *this == d;
}
bool Date::operator>(const Date& d)
{
	return !(*this <= d);
}
bool Date::operator>=(const Date& d)
{
	return !(*this < d);
}
bool Date::operator==(const Date& d)
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

bool Date::operator!=(const Date& d)
{
	return !(*this == d);
}

2. 日期类的相减

两个日期类的相减,有两种思路,其中第二种要简单很多

//日期类的相减
// d1 - d2
int Date::operator-(const Date& d)
{
	Date max = *this;
	Date min = d;
	int flag = 1;  // 前一个数假设都是大的数

	if (*this < d)
	{
		max = d;
		min = *this;
		flag = -1;
	}

	int day = 0;
	while (min != max)
	{
		++day;
		++min;
	}
	return day * flag;
}

3. 流输入输出重载

输出:

如果是函数声明在类内,会默认传一个形参this,而第一个参数默认是out,变成了d<<out

所以输入输出重载放在类外

类的成员变量设置成了private,访问不了,所以在类添加该函数为友元函数(这样就可以访问类中的成员变量了)

为了能够连续输出,必须返回out;

输入
为了判断输入的日期是否正确,在日期类Date.h中添加检查函数

同样在Date.h的日期类中添加友元函数

Date.cpp:

Test.cpp

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值