C++赋值运算符重载

赋值运算符重载

很巧妙的是,在编写这篇文章时(2023年2月27日),再加100天就是6月7日,恰好是今年高考的百日誓师!
(文章最后会阐述为什么要加100天)

C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。

函数名字为:关键字operator后面接需要重载的运算符符号

函数原型: 返回值类型 operator操作符(参数列表)

示例1:

例如我们在Date类中比较两个日期是否相等:

bool operator==(const Date& d1,const Date& d2)
{
    return d1._year==d2._year
        &&d1._month==d2._month
        &&d1._day==d2._day;
}

即:

这里的:

d1==d2;    //转换成operator==(d1,d2);(由编译器完成)

上述对于比较的结果,可更改为:(注意运算符的优先级)

image-20230227135706111


问题:若属性是私有的,怎么访问呢?

方式一:设置一个共有的get方法

方式二:放到类里面

//更改如下:
bool operator==(const Date& d)
{
    return _year==d._year
        &&_month==d._month
        &&_day==d._day;
}
示例2:

我们再来尝试Date类日期间大于小于的比较:

//放在类里面的
bool operator>(const Date& d)
{
	if (_year > d._year)
	{
		return true;
	}
	else if (_year == d._year && _month > d._month)
	{
		return true;
	}
	else if (_year == d._year && _month == d._month && _day > d._day)
	{
		return true;
	}

	return false;
}
示例3:

Date类日期间的大于等于:

bool operator>=(const Date& d)
{
    //this代表d1的地址,因此对this解引用即指向d1
    //复用上述已经书写的大于和等于的判定
    return *this>d||*this==d;
}
示例4:

日期加天数怎么办呢?(例如算某天过100天之后的日期)

函数名:operator+
参数:(int day)
返回类型:Date

得到每个月的天数;天满了进月,月满了进年

Step1:得到每个月的天数(判定是平年还是闰年)

int GetMonthDay(int year,int month)
{
    static int monthDayArray[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};//平年
    if(month==2 && (year%4==0&&year%100!=0)||year%400==0)                //闰年
    {
        return 29;
    }
    else
    {
        return monthDayArray[month];
    }
}

Step2:加上天数

Date operator+=(int day)
{
 	_day+=day;
    //日进
    while(_day>GetMonthDay(year,month))
    {
        _day-=GetMonthDay(year,month);
        _month++;
        //月进
        if(_month==13)
        {
            _year++;
            _month=1;
        }
    }
    return *this;
}

因此结果如下:

image-20230227170645274

很巧妙的是,在编写这篇文章时(2023年2月27日),再加100天就是6月7日,恰好是今年高考的百日誓师!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值