当前位置:网站首页>Classes and objects (3)
Classes and objects (3)
2022-06-11 21:44:00 【Code loving students】
Catalog
1.1 Assignment operator overload
1.8 In front of ++ And post ++
1.9 In front of -- And post --
1. operators overloading
C++ In order to enhance the readability of the code, operator overloading is introduced , Operator overloading is a function with a special function name , Also has its return value class type , Function name and parameter list , Its return value type and parameter list are similar to ordinary functions .
The function name is : keyword operator Followed by operator symbols that need to be overloaded .
The function prototype : return type operator The operator ( parameter list )
Here we use Date Class to do the following
class Date
{
public:
// Overload the operator
//...
private:
int _year;
int _month;
int _day;
};Be careful :
1. You can't create a new operator by connecting other symbols : such as operator ^ 、[email protected] etc. , Only existing operators can be overloaded .
2. .* 、::( Scope accessor ) 、sizeof() 、?:( ternary operators ) 、.( spot ) above 5 Operators cannot be overloaded .
1.1 Assignment operator overload
Be careful :
1. Assignment operator Can only As class
When the assignment operator is not explicitly implemented in a class , The compiler will generate a default , At this time, the user overloads the assignment operator outside the class , It conflicts with the default assignment operator generated by the compiler , Therefore, the assignment operator can only Overloaded into member functions .
2. Assignment operators are not equivalent to copy constructors

Is this a call to the assignment operator or a copy construct ?

We found that we ended up in the copy constructor .
It shows that when the object is initialized, the operator called by the assignment operator is not the overloaded operator , Instead, call the copy constructor ,
The assignment operator is called again only after the object has been initialized , Will use the overloaded operator .
Then how can we achieve ?
Date& operator=(const Date& d) {
if (this != &d) {
_year = d._year;
_month = d._month;
_day = d._day;
return *this;
}
}Here we also use the parameter with reference and return value with reference learned in the previous section .
Return value with reference Even if there is a function, it still exists , therefore Return alias Don't worry about illegal access .
Parameter with reference Is to avoid the infinite recursion problem .
1.2 == operators overloading
In built-in types == Is to compare the values in the two sides , The same is true in custom types , However, custom types cannot be compared directly like built-in types , Because there are built-in types and user-defined types in user-defined types , In the use of == when , It needs to be overloaded .
bool operator==(const Date& d) {
return _year == d._year && _month == d._month && _day == d._day;
}1.3 != operators overloading
!= The operator , When the two sides are not equal, return true, When both sides are equal, return false, Isn't that what == The opposite value of the operator
bool operator != (const Date& d) {
return !(*this == d);
}Here we use the function Principle of reusability , It greatly reduces the amount of our code and makes the code clearer .
1.4 < operators overloading
Similarly, when all member variables in a custom type are < return true, Otherwise return to false
bool operator < (const Date& d) {
if (_year < d._year || (_year == d._year && _month < d._month) ||
(_year == d._year && _month == d._month && _day < d._day)) {
return true;
}
return false;
}1.5 <= operators overloading
As long as it is less than or equal to any one, it returns true, Otherwise return to false
bool operator <= (const Date& d) {
return (*this<d)||(*this==d)
}1.6 > The operator
> The antonym of is <=, Also take advantage of reusability
bool operator>(const Date& d) {
return !(*this<=d);
}1.7 >= The operator
We can use >= The antonym of is < To write , You can also use > and = Meet a condition to write
bool operator >= (const Date& d) {
//return (*this>d)||(*this==d);
return !(*this < d);
}1.8 In front of ++ And post ++
In the face of ++ When the operator is overloaded , In the form of :operator++(), How do we distinguish when to use prepositions ++, When to use post ++ Well ?
For pre ++ Do not write parameters , In the form of :operator++()
For post ++ Write parameters , In the form of :operator++(int i)
The type of parameter is well specified , We just need to do it , Don't think too much .
Let's first look at ++
Date& operator++() {
*this += 1;
return *this;
}In front of ++ We just need to remember first ++ Reuse
After ++
Date operator++(int i) {
Date ret(*this);
*this += 1;
return ret;
}First create an object to copy the current value , And then again ++, Return the created temporary object .
1.9 In front of -- And post --
And 1.8 Empathy , Attach code
// In front of --
Date& operator++() {
*this -= 1;
return *this;
}
// After --
Date operator--(int i) {
Date ret(*this);
*this -= 1;
return ret;
}
If the return value can have & best , Because there can be one less copy step , The rate of increase , Therefore, the belt can be used & Use on return &.
2. Write a Date class
I learned so much about operator overloading and previous related knowledge , We can write a completed class
class Date
{
public:
// Judgement of leap year
bool judge(int year) {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
return true;
}
return false;
}
// Gets the number of days in a month of a year
int GetMonthDay(int year, int month) {
int MonthDayArrays[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
if (month == 2 && judge(year)) {
return 29;
}
return MonthDayArrays[month];
}
// All default constructors
Date(int year = 1900, int month = 1, int day = 1) {
if (year >= 1 && month >= 1 && month <= 12 &&
day >= 1 && day <= GetMonthDay(year, month)) {
_year = year;
_month = month;
_day = day;
}
}
void print() {
cout << _year <<"-"<< _month << "-"<<_day << endl;
}
// copy constructor
// d2(d1)
Date(const Date& d) {
_year = d._year;
_month = d._month;
_day = d._day;
}
// Assignment operator overload
// d2 = d3 -> d2.operator=(&d2, d3)
Date& operator=(const Date& d) {
if (this != &d) {
_year = d._year;
_month = d._month;
_day = d._day;
return *this;
}
}
// Destructor
//~Date();
// date += Days
Date& operator+=(int day) {
if (day < 0) {
return *this -= -day;
}
_day += day;
while (_day > GetMonthDay(_year, _month)) {
_day -= GetMonthDay(_year, _month);
_month++;
if (_month == 13) {
_year++;
_month = 1;
}
}
return *this;
}
// date + Days
Date operator+(int day) const {
Date ret(*this);
ret += day;
return ret;
}
// date - Days
Date operator-(int day) const {
Date ret(*this);
ret -= day;
return ret;
}
// date -= Days
Date& operator-=(int day) {
if (day < 0) {
return *this += -day;
}
_day -= day;
while (_day <= 0) {
--_month;
if (_month == 0) {
_year--;
_month = 12;
}
_day += GetMonthDay(_year, _month);
}
return *this;
}
// > Operator overloading
bool operator>(const Date& d) {
if (_year > d._year || (_year == d._year && _month > d._month) ||
(_year == d._year && _month == d._month && _day > d._day)) {
return true;
}
return false;
}
// == Operator overloading
bool operator==(const Date& d) {
return _year == d._year && _month == d._month && _day == d._day;
}
// >= Operator overloading
inline bool operator >= (const Date& d) {
return !(*this < d);
}
// < Operator overloading
bool operator < (const Date& d) {
if (_year < d._year || (_year == d._year && _month < d._month) ||
(_year == d._year && _month == d._month && _day < d._day)) {
return true;
}
return false;
}
// <= Operator overloading
bool operator <= (const Date& d) {
return !(*this>d);
}
// != Operator overloading
bool operator != (const Date& d) {
return !(*this == d);
}
// date - date Return days
int operator-(const Date& d) {
int temp = 0;
Date max = d;
Date min = *this;
int flag = -1;
if (*this>d)
{
max = *this;
min = d;
flag = 1;
}
for (int i = min._year; i < max._year; i++) {
temp += judge(i) ? 366 : 365;
}
for (int i = 1; i < max._month; i++) {
temp += GetMonthDay(d._year, i);
}
for (int i = 1; i < min._month; i++) {
temp -= GetMonthDay(_year, i);
}
temp += max._day - min._day;
return temp*flag;
}
private:
int _year;
int _month;
int _day;
};
Complete a small exercise !!
边栏推荐
- How to use RPA robot to start the first step of digital transformation of freight forwarding industry?
- In the future, cloud expansion technology is expected to be selected as a specialized, special and new enterprise in Shanghai
- 剑指Offer 29.顺时针打印矩阵
- Building a custom CNN model: identifying covid-19
- 类与对象(3)
- LeetCode-104-二叉树的最大深度
- 线性表的链式存储结构
- Leetcode-32- longest valid bracket
- LeetCode-110-平衡二叉树
- Flutter series: detailed explanation of container layout commonly used in flutter
猜你喜欢
随机推荐
继承的所有特征
189. 轮转数组
实验10 Bezier曲线生成-实验提高-控制点生成B样条曲线
Leetcode-129- sum of numbers from root node to leaf node
「大模型」之所短,「知识图谱」之所长
Parker plunger pump pv180r1k1t1nmmc
Master of a famous school has been working hard for 5 years. AI has no paper. How can the tutor free range?
EndnoteX9简介及基本教程使用说明
Building a custom CNN model: identifying covid-19
Cdr2022 serial number coreldraw2022 green key
RPA+低代码为何是加速财务数字化转型之利器?
How to import workflows provided on SAP API hub to sap BTP
Relatively perfect singleton mode
快速排序的优化
The upcoming launch of the industry's first retail digital innovation white paper unlocks the secret of full link digital success
关于斜率优化
Usage of esp32c3 Arduino Library
AC automata
二分查找 - 学习
LeetCode-110-平衡二叉树








![[Part 13] source code analysis and application details of completabilefuture class [key]](/img/cf/87c60a1d46835f3f0dae9f44970de4.jpg)