当前位置: 首页 > news >正文

C++学习记录——유 类和对象(3)

文章目录

  • 1、赋值运算符重载
    • 1、运算符重载
      • 1、理解
      • 2、运算符重载实例
    • 2、赋值运算符重载
  • 2、日期类的实现
    • 1、加减函数
      • 1、加函数
      • 2、减函数
    • 2、前/后置++--重载
    • 3.两个日期相减
  • 其他
    • 1、流插入
    • 2、流提取


日期类的整体实现代码: https://gitee.com/kongqizyd/start-some-c-codes-for-learning.c/tree/master/%E6%97%A5%E6%9C%9F%E7%B1%BB

关于日期类的讲解会比较长,可以边看完整代码边看分析

1、赋值运算符重载

1、运算符重载

1、理解

继续用日期类做例子。

class Date
{
public:Date(int year = 2023, int month = 1, int day = 1){_year = year;_month = month;_day = day;}
private:int _year;int _month;int _day;
};

假设现在要比较两个日期数值大小

int main()
{Date d1(2023, 2, 8);Date d2;return 0;
}

我们自然可以定义一个函数,参数类型就是Date类或者说Date的引用类,用来比较两个变量。但这样有些俗套了,或者说很常见的做法,C++有自定义类型和内置类型,内置类型的比较很简单,而自定义类型的比较需要程序员自己确定如何比较。C++对此有运算符重载函数,用到关键字operator。现在写一个比较相等的函数。

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

要把他当做一个正常的函数,并且d1和d2的位置也就是在main调用这个函数时的位置,d1 == d2即可调用。这里先把三个变量变成公有类型才能在外部访问。

d1 == d2;
operator==(d1, d2);

调用时这两种写法都可,不过第一个更简单。第一个对于程序,会及时地转换成operator==(d1, d2)。

但是如果想打印结果,不能用d1 == 2,因为实际写出来时,<< >>运算符优先级高于等于号,所以需要括起来。

现在是把这个函数放到全局里,所以类里的成员变量要换成公有的才行。而另一个办法就是把这个函数放到类里面也可,但如果直接放进去编译器就会告诉你参数放多了,因为本身是有this指针的,所以括号里放一个参数即可。

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

调用时这样写就行

cout << d1.operator==(d2) << endl;

运算重载特征:
不能通过连接其他符号来创建新的操作符:比如operator@
重载操作符必须有一个类类型参数
用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不 能改变其含义
作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this
.* :: sizeof ?: . 注意以上5个运算符不能重载。这个经常在笔试选择题中出
现。

2、运算符重载实例

写一下小于的函数。

	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;elsereturn false;

当然也可以放到一块,直接就是return一串代码。

cout << d1.operator<(d2) << endl;

这样就可以检验一下结果。

不过我们还有一个更简单地写法。比如写小于等于的函数

	bool operator<=(const Date& d){return *this < d || *this == d;}

大于等于

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

不能出现*this > d,编译器会报出一堆错。

在这里插入图片描述

2、赋值运算符重载

现在要把d2的值赋值给d1.

	void operator=(const Date& d){_year = d._year;_month = d._month;_day = d._day;}

这里不用引用也可以,因为我们写好的拷贝构造函数是一个成熟的函数,用引用传参,而这里传参,调用完拷贝构造就好了,不过用一下引用能省点编译器工作。

但是这样不是赋值的完整函数。在C语言中,我们可以连续赋值,也就是x = y = z,如果按照这样写,一定会出错。这里的实现思路就是z赋值给y后要返回一个值,返回的这个值再赋值给x,这个返回值其实也就是y。

	Date& operator=(const Date& d){_year = d._year;_month = d._month;_day = d._day;return *this;}

还有一个问题,有可能会出现自己给自己赋值,所以加个判断。

		if (this != &d){_year = d._year;_month = d._month;_day = d._day;}

如果不写重载,编译器还是会自己生成,规则还是一样,有资源申请才需要自己写。

拷贝构造会这样写:
Date d2 = d1;
Date d2(d1);

重载需要一个Date类型的变量,而拷贝构造可以不需要,所以重载不能这样写,Date d2 = d1。

2、日期类的实现

现在写一个比较全的日期类。

<Date.h>

#pragma once
#include <iostream>
using namespace std;class Date
{
public:Date(int year = 2023, int month = 1, int day = 1);void Print();bool operator==(const Date& d);bool operator!=(const Date& d);bool operator<(const Date& d);bool operator<=(const Date& d);bool operator>=(const Date& d);bool operator>(const Date& d);//Date& operator=(const Date& d);private:int _year;int _month;int _day;
};

<Date.cpp>

#include "Date.h"Date::Date(int year, int month, int day)
{_year = year;_month = month;_day = day;
}void Date::Print()
{cout << _year << "/" << _month << "/" << _day << endl;
}bool Date::operator==(const Date& d)
{return _year == d._year&& _month == d._month&& _day == d._day;
}bool Date::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;elsereturn 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 !(*this == d);
}

<Test.cpp>

#include "Date.h"void Test1()
{Date d1(2023, 2, 8);d1.Print();Date d2(2023, 2, 28);d2.Print();
}int main()
{Test1();return 0;
}

针对初始化日期的函数,有一个现实问题没有想到,就是如果年是负数呢?或者其它数是一个不可能的数呢?所以要加上检查函数,比如上一篇的我GetDay等函数。

int GetMonthDay(int year, int month)
{int monthArr[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 monthArr[month];}
}Date::Date(int year, int month, int day)
{if (month > 0 && month < 13 && (day > 0 && day <= GetMonthDay(year, month))){_year = year;_month = month;_day = day;}elsecout << "日期非法" << endl;
}

1、加减函数

1、加函数

写上相加的函数,这里的思路也和上一篇一样,有了返回值,+=也可以连续+=。如果这样写:Date d2 = d1 += 100,是会把d1也给改变。

Date& Date::operator+=(int day)
{_day += day;while (_day > GetMonthDay(_year, _month)){_day -= GetMonthDay(_year, _month);_month++;if(_month == 13){++_year;_month = 1;}}return *this;
}
	Date d2 = d1;d2 += 100;d2.Print();d1.Print();

再写上+。

Date Date::operator+(int day)
{Date tmp(*this);tmp._day += day;while (tmp._day > GetMonthDay(tmp._year, tmp._month)){tmp._day -= GetMonthDay(tmp._year, tmp._month);tmp._month++;if (tmp._month == 13){++_year;tmp._month = 1;}}return tmp;
}
	Date d3 = d1 + 100;d3.Print();d1.Print();

用临时变量tmp,防止d1被改变。

出了作用域,*this存在,所以可以用引用,而tmp不存在,不能用引用。也可以在tmp前加上static,也不能用引用,d1为最一开始的数据,d2 = d1 + 100,没有问题,但是同样的,静态区里的这个tmp没有清除,它会接着上一次数据继续加,所以后面再来个d3 = d1 + 100就不是正确数据了。静态变量只会初始化一次,所以再次调用就不会被初始化。

+=和+的代码有些像,我们简化一下

Date Date::operator+(int day)
{Date tmp(*this);tmp += day;/*tmp._day += day;while (tmp._day > GetMonthDay(tmp._year, tmp._month)){tmp._day -= GetMonthDay(tmp._year, tmp._month);tmp._month++;if (tmp._month == 13){++_year;tmp._month = 1;}}*/return tmp;
}

+里面用+=。+=也可以使用+。

*this = *this + day;

不过实现+=,+里面放+=更好。因为+本身有拷贝,*this = *this + day还会有赋值。

2、减函数

减去天数,我们要往前倒月,倒年,先把年或者月给减好,然后再去获取天数。

Date& Date::operator-=(int day)
{_day -= day;while (_day <= 0){--_month;if (_month == 0){--_year;_month = 12;}_day += GetMonthDay(_year, _month);}return *this;
}Date Date::operator-(int day)
{Date tmp(*this);tmp -= day;
}

加减函数齐全后,有些问题就可以解决。d2 += -100,如果还是之前的代码,那么最终的结果不切实际,转换一下就是d2 -= 100,所以在每个函数开头,我们还需要加上判断。

Date& Date::operator+=(int day)
{//*this = *this + day;if (day < 0){*this -= -day;return *this;}_day += day;while (_day > GetMonthDay(_year, _month)){_day -= GetMonthDay(_year, _month);_month++;if(_month == 13){++_year;_month = 1;}}return *this;
}

另外三个也是如此。

2、前/后置+±-重载

前置++比较简单,可以用引用,传入数据后+1,然后返回即可。

Date& Date::operator++()
{*this += 1;return *this;
}

后置++需要注意些,我们要返回一个+1之前的值,所以需要调用拷贝构造,创建一个临时变量。

Date Date::operator++(int)
{Date tmp(*this);*this += 1;return tmp;
}

至于编译器如何辨别是前还是后,这自有办法,不过为了构成重载,声明的时候后置会在括号里写上int,不必写变量名,仅供编译器区分用。实际比较起来,前置++还是更简单,不需要调用其他,一般情况下前置++用得比较多。

	Date& operator++();//前置++Date operator++(int);//后置++,int只是为了占位,和前置函数构成重载
void Test2()
{Date d1(2023, 2, 8);d1.Print();++d1;//前置正常++d1++;//后置会传一个形参类型的参数
}

–是这样写

Date& Date::operator--()
{*this -= 1;return *this;
}Date Date::operator--(int)
{Date tmp(*this);*this -= 1;return tmp;
}

测试的时候可以显式调用

d1.operator++(0);

3.两个日期相减

用int类型的减函数。

声明:int operator-(const Date& d);

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 n = 0;while (min != max){++min;++n;}return n * flag;
}

测试代码

void Test5()
{Date d1(2023, 2, 8);d1.Print();Date d2(2002, 8, 4);d2.Print();cout << d1 - d2 << endl;
}

其他

1、流插入

像上面的Print函数,可不可cout打印呢?Print函数里是用cout实现的,那么可不可以直接cout << d1?实际上不行,但如果后面跟的是一个内置类型的变量,cout就可以了。C++有osream这个类,类里有cout等成员函数,但和默认成员函数不同,它们即使不写也有默认的函数,而其他成员函数就必须要写,ostream类已经写好了常用变量类型的函数重载,并且也写了<<的运算符重载,所以我们在用cout打印时不需要担心类型,因为C++已经写好了。

那么我们想用cout打印自定义类型的数据,那就需要自己写,写到自己的类里。

void Date::operator<<(ostream& out)
{out << _year << "年" << _month << "月" << _day << "日" << endl;
}

这样写出来,括号还是有两个参数,但是第一个参数是默认的*this,也就是外部声明的d1这些变量。运算符重载写的时候,要按照参数顺序写,所以最后就是d1 << cout。这样有些奇怪,不是我们平常见到的那样,那么把他从类里拿出来写就可以控制顺序了,但这样就会有一个问题,成员变量无法访问,除去把他们变公有外,还可以添加友元函数。

声明:void operator<<(ostream& out, const Date& d);

类里这样写

	//友元friend void operator<<(ostream& out, const Date& d);

定义:

void operator<<(ostream& out, const Date& d)
{out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
}

测试代码

	operator<<(cout, d1);cout << d1;

平常写流插入的时候很多都是连续写,所以还需要改进,要有返回值。

ostream& operator<<(ostream& out, const Date& d)
{out << d._year << "年" << d._month << "月" << d._day << "日" << endl;return out;
}

2、流提取

流提取的参数不能加const,加const的作用是为了减少拷贝。

声明: istream& operator>>(istream& in, Date& d);
friend istream& operator>>(istream& in, Date& d);

定义

istream& operator>>(istream& in, Date& d)
{in >> d._year >> d._month >> d._day;return in;
}

测试代码

void Test7()
{Date d1;cin >> d1;cout << d1;
}

为了更简洁,我们可以用内联函数。实际上在类里面定义的成员函数,就默认为内联函数。那么Date.cpp文件里可以不写,把定义放到.h文件里,前面加上inline

inline ostream& operator<<(ostream& out, const Date& d)
{out << d._year << "年" << d._month << "月" << d._day << "日" << endl;return out;
}inline istream& operator>>(istream& in, Date& d)
{in >> d._year >> d._month >> d._day;return in;
}

本篇最一开始给的链接可以看到全部的代码,里面出现的const可以暂且不管,下一篇会写出为什么加const。

结束。

http://www.lryc.cn/news/897.html

相关文章:

  • 基于Hi3861平台的OpenHarmony程序是如何启动运行的
  • 2023彻底解决Typora使用iPic微博图床失效问题
  • Revit中添加水平仰视平面图及水平剖面
  • Python 循环语句
  • 使用 ThreeJS 实现第一个三维场景(详)
  • 《小猫猫大课堂》三轮5——动态内存管理(通讯录动态内存化)
  • 【Selenium学习】Selenium 八大定位法
  • 算法训练营 day41 贪心算法 单调递增的数字 买卖股票的最佳时机含手续费
  • 【数据结构-JAVA】排序
  • 基于注解管理Bean
  • Containerd 的 Bug 导致容器被重建!如何避免?
  • win环境安装部署Jenkins
  • 网络变压器与不同芯片之间的匹配原则及POE通讯产品需要注意哪些方面
  • Spring WebFlux
  • C++基础面试题:new和malloc的区别
  • WebDAV之葫芦儿·派盘+KMPlayer
  • 杨浦区人工智能及大数据(云计算)企业登记工作(2023年度)的通知
  • 2023年去培训机构学前端还是Java?
  • 【React】组件事件
  • 黑/白盒测试说明
  • 车道线检测-Eigenlanes 论文学习笔记
  • docker run mysql -e 的环境变量 Environment Variables
  • 第17章 MongoDB 条件操作符教程
  • 电子技术——共源共栅放大器
  • 《MySQL学习》 事务隔离 与 MVCC
  • html(二)基础标签
  • leetcode刷题---递归思想
  • ThreadLocal 源码级别详解
  • 训练营day17
  • Nodejs原型链污染