类和对象(4):Date类.运算符重载 1

一、赋值运算符重载

1.1 运算符重载

运算符重载是具有特殊函数名的函数,函数名字为:关键词operator+需要重载的运算符符号

  1. 不能重载C/C++中未出现的符号,如:operator@
  2. 重载操作符必须有一个类类型参数。
  3. 不能改变用于内置类型运算的运算符其具有的含义。
cpp 复制代码
// 以下代码只是为了举例,本质是错误的
int operator+(int a, int b)
{
    return a - b;// error
}
  1. 作为类成员函数重载时,第一个参数为隐藏的this
  2. .*::sizeof、三目运算符?:.,以上5个预算符不能被重载。
1.2 Date类举例

重点为运算符重载中关键的细节。

cpp 复制代码
// Date.h
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	void Print()
    {
        cout << _year << " " << _month << " " << _day << endl;
	}
    
    int GetMonthDay(int year, int month)// 获取当年当月有多少天
	{
        assert(month >= 1 && month <= 12);
        int Day[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        if (month == 2 && (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)))
        {
            return 29;
        }
		return Day[month];
	}

	Date& operator+=(int x);
	Date operator+(int x);

private:
	int _year;
	int _month;
	int _day;
};
cpp 复制代码
// Date.cpp
Date& Date::operator+=(int x)// operator+=(Date* this, int x)
{
	_day += x;
	while (_day > GetMonthDay(_year, _month))
	{
		_day -= GetMonthDay(_year, _month);
		_month++;
		if (_month == 13)
		{
			_year++;
			_month = 1;
		}
	}
	return *this;
}

Date Date::operator+(int x)
{
	Date tmp(*this);
	tmp += x;
	return tmp;
}
  1. +=重载的重点为返回值类型为Date&*this在函数调用结束后并没有被销毁,传引用返回可以避免创建临时对象。
  2. 调用+重载时,对象本身不被改变,因此需要拷贝一个临时对象完成运算。
相关推荐
秋田君1 小时前
Qt_QMediaPlayer类与QMediaPlaylist类
开发语言·qt
统计学小王子1 小时前
数学建模国赛倒计时6天——《软件工具(R语言精讲)》
开发语言·数学建模·r语言
C++ 老炮儿的技术栈1 小时前
Qt5 使用 QPainter 绘制阿基米德螺线
开发语言·c++·windows·qt·代码化
EasyGBS1 小时前
从接入到稳定播放:无插件直播H5视频流媒体播放器EasyPlayer.js如何撑起Web端流媒体
开发语言·前端·javascript
FfHUCisI1 小时前
GMP 调度器:Go 并发的心脏是如何跳动的
开发语言·golang·php
Java小白笔记1 小时前
Java 实现阿里云 OSS 文件上传链路:普通上传、秒传、分片与断点续传
java·开发语言·数据库·spring·阿里云
传奇开心果编程1 小时前
【Rust入门知识点学与练】第9课:Vec 动态数组
开发语言·学习·rust
卢锡荣1 小时前
单芯掌控多口互联|乐得瑞 LDR6020 PD3.1 多通道 Type‑C 控制 SOC 芯片
c语言·开发语言
2333!!!!!1 小时前
rocket新手一些常见问题
java·开发语言
yume_sibai1 小时前
02-Rust 所有权与借用深入解析(底层原理 + 借用检查器 + 生命周期 + 内部可变性)
开发语言·后端·rust