当前位置:网站首页>A preliminary understanding of operator overloading
A preliminary understanding of operator overloading
2022-07-01 01:59:00 【changgzhu】
Catalog
2.1 Application of operator overloading
2.2 Assignment operator overload
One . Operator overloading
1.1 Concept
C++ In order to enhance the readability of the code, operator overloading is introduced , Operator overloading is a function with a special function name , It also has its return value type , Function name and parameter list , Its return value type and parameter list are similar to ordinary functions .
Generally speaking, it means : Built in type (int,double), You can directly use various operators (=,+)
Custom type , You can't use all kinds of operators directly
In order to customize the type, you can use various operators , Make rules for operator overloading
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 )
Be careful :
- You can't create a new operator by connecting other symbols : such as [email protected]
- The overload operator must have an operand of class type or enumeration type
- Operators for built-in types , Its meaning cannot be changed , for example : Built in integer +, No Can change its meaning
- .* 、:: 、sizeof 、?: 、. Pay attention to the above 5 Operators cannot be overloaded .
2.1 Application of operator overloading
Use the date as an example
#pragma once
#include <iostream>
#include <assert.h>
using std::cout;
using std::cin;
using std::endl;
class Date
{
public:
// Decide if it's a leap year
bool isLeapYear(int year) {
if ((year%4==0&&year%100!=0)||year%400==0)
{
return true;
}
else
{
return false;
}
}
// Gets the number of days in a month of a year
int GetMonthDay(int year, int month);
// All default constructors
Date(int year = 2000, int month = 1, int day = 2);
void Print() {
cout << _year << "-" << _month << "-" << _day << endl;
}
// date - date Return days
int operator-(const Date& d);
// date += Days
Date& operator+=(int day);
// date + Days
Date operator+(int day);
// date - Days
Date operator-(int day);
// date -= Days
Date& operator-=(int day);
// In front of ++
Date& operator++() {
*this += 1;
return *this;
}
// After ++
Date operator++(int) {
*this += 1;
return *this;
}
// After --
Date operator--(int) {
*this -= 1;
return *this;
}
// In front of --
Date& operator--() {
*this -= 1;
return *this;
}
// > Operator overloading
bool operator>(const Date& d);
// == Operator overloading
bool operator==(const Date& d);
// >= Operator overloading
bool operator >= (const Date& d) {
return *this == d || *this > d;
}
// < Operator overloading
bool operator < (const Date& d) {
return !(*this > d || *this == d);
}
// <= Operator overloading
bool operator <= (const Date& d) {
return !(*this > d);
}
// != Operator overloading
bool operator != (const Date& d) {
return !(*this == d);
}
private:
int _year;
int _month;
int _day;
};#include "Date.h"
int Date:: GetMonthDay(int year, int month) {
assert(year > 0 && month > 0 && month < 13);// Assert illegal date
static int monthDayArray[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (month == 2 && isLeapYear(year))
{
return 29;
}
else
{
return monthDayArray[month];
}
}
Date::Date(int year, int month, int day) {
if (year >= 1 &&
month <= 12 && month >= 1 &&
day >= 1 && day <= GetMonthDay(year, month))
{
_year = year;
_month = month;
_day = day;
}
else
{
cout << " Illegal date " << endl;
}
}2.1.1 Monocular operators
Single valued operands are commonly used :++,--,+,- etc.
Be careful : When overloading a function as a member of a class , Its parameters look less than the operands 1 The operator of a member function has a default formal parameter this, Limited to the first parameter .
++
// After ++
Date operator++(int) {// there int It doesn't mean much , It is equal to a signal , Let the compiler understand that this is post ++
Date tmp(*this);
*this += 1;
return tmp;
}
// In front of ++
Date& operator++() {
*this += 1;
return *this;
}--
// After --
Date operator--(int) {
Date tmp(*this);
*this -= 1;
return tmp;
}
// In front of --
Date& operator--() {
*this -= 1;
return *this;
}
+
Date Date:: operator+(int day) {
Date ret = (*this);
ret. _day += day;
// Judge whether to carry
while (ret._day>GetMonthDay(ret._year,ret._month))
{
ret. _day -= GetMonthDay(ret._year, ret._month);
ret. _month++;
if (ret._month==13)
{
ret. _month = 1;
ret._year++;
}
}
return ret;// This local variable , Cannot return by reference
}-
Date Date:: operator-(int day) {
if (day<0)
{
return *this + (-day);// Reuse +
}
Date ret = *this;
ret._day -= day;
while (ret._day<=0)
{
ret._month--;
if (ret._month==0)
{
ret._month = 12;
ret._year--;
}
ret._day += GetMonthDay(ret._year, ret._month);
}
return ret;
}2.1.2 Relational operator
Be careful : When overloading a function as a member of a class , Its parameters look less than the operands 1 The operator of a member function has a default formal parameter this, Limited to the first parameter .
Relational operators have :>,<,==,>=,<= etc.
The code here only needs to implement >. and == Code , Others can be reused
>
bool Date:: operator>(const Date& d) {
if ((_year>d._year)
||(_year==d._year&&_month>d._month)||(_month==d._month&&_day>d._day))
{
return true;
}
else
{
return false;
}
}==
bool Date:: operator==(const Date& d) {
return _year == d._year && _month == d._month
&& _day == d._day;
}<
// < Operator overloading
bool operator < (const Date& d) {
return !(*this > d || *this == d);
}<=
// <= Operator overloading
bool operator <= (const Date& d) {
return !(*this > d);
}>=
// >= Operator overloading
bool operator >= (const Date& d) {
return *this == d || *this > d;
}!=
// != Operator overloading
bool operator != (const Date& d) {
return !(*this == d);
}2.2 Assignment operator overload
Typical assignment operators :=,+=,-= etc. .
= Operator overloading is the default function , We don't have to write it ourselves , Others need to be written by ourselves
But there are some caveats :

Of course, it can also be written , The code is as follows :
//= Operator overloading
Date& operator =(const Date& d) { // Reduce copy construction with references
if (this != &d)// Check whether you assign values to yourself
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;// Return value
}Be careful : This is just a shallow copy , That is, value copy .
Here we can reuse the above directly + and - overloaded , Write += and -= Overloaded functions for
+=
Date& Date:: operator+=(int day) {
*this = *this + day; // Reuse + and =
return *this;
}-=
Date& Date:: operator-=(int day) {
*this = *this - day; // Reuse - and =
return *this;
}2.3 Subtraction of date
Date minus date gets days , Date plus date. Well, it doesn't mean anything .
The general idea is that small dates continue ++, Until it is equal to the big date .
int Date:: operator-(const Date& d) {
int flaght = 1; //flaght Judgment is big - Small , It's still small - Big .
Date max = *this;
Date min = d;
if (*this<d) // Guarantee big date max, The minor date is min
{
min = *this;
max = d;
flaght = -1;
}
int count = 0;
while (min!=max)
{
++count;// Count how many days are equal
++min;// Reuse the front ++
}
return count*flaght; // Small - Big is a negative number
}3 Master code
#pragma once
#include <iostream>
#include <assert.h>
using std::cout;
using std::cin;
using std::endl;
class Date
{
public:
// Decide if it's a leap year
bool isLeapYear(int year) {
if ((year%4==0&&year%100!=0)||year%400==0)
{
return true;
}
else
{
return false;
}
}
// Gets the number of days in a month of a year
int GetMonthDay(int year, int month);
// All default constructors
Date(int year = 2000, int month = 1, int day = 2);
void Print() {
cout << _year << "-" << _month << "-" << _day << endl;
}
// date - date Return days
int operator-(const Date& d);
// date += Days
Date& operator+=(int day);
// date + Days
Date operator+(int day);
// date - Days
Date operator-(int day);
// In front of ++
Date& operator++() {
*this += 1;
return *this;
}
// After ++
Date operator++(int) {
Date tmp(*this);
*this += 1;
return tmp;
}
// After --
Date operator--(int) {
Date tmp(*this);
*this -= 1;
return tmp;
}
// In front of --
Date& operator--() {
*this -= 1;
return *this;
}
// > Operator overloading
bool operator>(const Date& d);
// == Operator overloading
bool operator==(const Date& d);
// >= Operator overloading
bool operator >= (const Date& d) {
return *this == d || *this > d;
}
// < Operator overloading
bool operator < (const Date& d) {
return !(*this > d || *this == d);
}
// <= Operator overloading
bool operator <= (const Date& d) {
return !(*this > d);
}
// != Operator overloading
bool operator != (const Date& d) {
return !(*this == d);
}
//= Operator overloading
Date& operator =(const Date& d) { // Reduce copy construction with references
if (this != &d)// Check whether you assign values to yourself
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;// Return value
}
// date -= Days
Date& operator-=(int day);
private:
int _year;
int _month;
int _day;
};#include "Date.h"
int Date:: GetMonthDay(int year, int month) {
assert(year > 0 && month > 0 && month < 13);
static int monthDayArray[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (month == 2 && isLeapYear(year))
{
return 29;
}
else
{
return monthDayArray[month];
}
}
Date::Date(int year, int month, int day) {
if (year >= 1 &&
month <= 12 && month >= 1 &&
day >= 1 && day <= GetMonthDay(year, month))
{
_year = year;
_month = month;
_day = day;
}
else
{
cout << " Illegal date " << 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)
||(_year==d._year&&_month>d._month)||(_month==d._month&&_day>d._day))
{
return true;
}
else
{
return false;
}
}
Date Date:: operator+(int day) {
Date ret = (*this);
ret. _day += day;
// Judge whether to carry
while (ret._day>GetMonthDay(ret._year,ret._month))
{
ret. _day -= GetMonthDay(ret._year, ret._month);
ret. _month++;
if (ret._month==13)
{
ret. _month = 1;
ret._year++;
}
}
return ret;
}
Date& Date:: operator+=(int day) {
*this = *this + day;
return *this;
}
Date Date:: operator-(int day) {
if (day<0)
{
return *this + (-day);// Reuse +
}
Date ret = *this;
ret._day -= day;
while (ret._day<=0)
{
ret._month--;
if (ret._month==0)
{
ret._month = 12;
ret._year--;
}
ret._day += GetMonthDay(ret._year, ret._month);
}
return ret;
}
Date& Date:: operator-=(int day) {
*this = *this - day;
return *this;
}
int Date:: operator-(const Date& d) {
int flaght = 1; //flaght Judgment is big - Small , It's still small - Big .
Date max = *this;
Date min = d;
if (*this<d) // Guarantee big date max, The minor date is min
{
min = *this;
max = d;
flaght = -1;
}
int count = 0;
while (min!=max)
{
++count;// Count how many days are equal
++min;
}
return count*flaght; // Small - Big is a negative number
}边栏推荐
- AS400 大厂面试
- Electron pit Addon
- 【做题打卡】集成每日5题分享(第一期)
- [无线通信基础-14]:图解移动通信技术与应用发展-2-第一代移动模拟通信大哥大
- In the fourth week of June, the list - flying melon data up main growth ranking list (BiliBili platform) was released!
- Short message sending solution in medical his industry
- Test essential tool - postman practical tutorial
- VirtualBox 安装增强功能
- Windows quick add boot entry
- Delete duplicate email
猜你喜欢

思特奇加入openGauss开源社区,共同推动数据库产业生态发展

Video tutorial | Chang'an chain launched a series of video tutorial collections (Introduction)

数学知识:求组合数 III—求组合数

3500字归纳总结:一名合格的软件测试工程师需要掌握的技能大全

Selenium经典面试题-多窗口切换解决方案

Working for eight years as a programmer, but with a salary of three years after graduation, it's too late to be enlightened again

机器学习10-信念贝叶斯分类器

AS400 API 从零到一的整个历程
![Pytorch —— 基础指北_贰 高中生都能看懂的[反向传播和梯度下降]](/img/6e/279dbb7a8d7a5ecd240de464c5b8b2.png)
Pytorch —— 基础指北_贰 高中生都能看懂的[反向传播和梯度下降]

Electron pit Addon
随机推荐
(翻译)使用眉状文本提高标题点击率
AS400 API 从零到一的整个历程
Live shopping mall source code, realize left-right linkage of commodity classification pages
RocketQA:通过跨批次负采样(cross-batch negatives)、去噪的强负例采样(denoised hard negative sampling)与数据增强(data augment
数据探索电商平台用户行为流失分析
[无线通信基础-15]:图解移动通信技术与应用发展-3- 数字通信2G GSM、CDMA、3G WDCMA/CDMA200/TD-SCDMA、4G LTE、5G NR概述
[content of content type request header]
[fundamentals of wireless communication-14]: illustrated mobile communication technology and application development-2-the first generation mobile analog communication big brother
System. Csrebot for commandline
Mathematical knowledge: finding combinatorial number IV - finding combinatorial number
Handsontable data grid component
522. 最长的特殊序列 II
Test essential tool - postman practical tutorial
Laravel event & subscription
Log4j2 ThreadContext日志链路追踪
What other hot spots are hidden under 1500W playback? Station B 2 future trends you can't miss
How to select securities companies? In addition, is it safe to open a mobile account?
SWT/ANR问题--Native方法执行时间过长导致SWT
Connectivity basis of Graphs
int和位数组互转