当前位置:网站首页>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
}边栏推荐
- Template: globally balanced binary tree
- laravel 事件 & 订阅
- go导入自建包
- 45 year old programmer tells you: why do programmers want to change jobs? It's too true
- 模板:全局平衡二叉树
- 静态域与静态方法
- 数学知识:求组合数 IV—求组合数
- In the fourth week of June, the list - flying melon data up main growth ranking list (BiliBili platform) was released!
- 【毕业季·进击的技术er】--毕业到工作小结
- 【JS】【掘金】获取关注了里不在关注者里的人
猜你喜欢

Analysis on user behavior loss of data exploration e-commerce platform

Ks009 implementation of pet management system based on SSH

远程办公如何保持高效协同,实现项目稳定增长 |社区征文

@ConfigurationProperties和@Value的区别

(translation) reasons why real-time inline verification is easier for users to make mistakes

Calculate special bonus

修复表中的名字(首字符大写,其他小写)

CorelDRAW 2022中文精简64位直装版下载

【JS】【掘金】获取关注了里不在关注者里的人

In the fourth week of June, the list - flying melon data up main growth ranking list (BiliBili platform) was released!
随机推荐
P6773 [noi2020] destiny (DP, segment tree merging)
Handsontable数据网格组件
[无线通信基础-15]:图解移动通信技术与应用发展-3- 数字通信2G GSM、CDMA、3G WDCMA/CDMA200/TD-SCDMA、4G LTE、5G NR概述
In the fourth week of June, the list - flying melon data up main growth ranking list (BiliBili platform) was released!
PHP array splicing MySQL in statement
【2022年】江西省研究生数学建模方案、代码
The latest CSDN salary increase technology stack in 2022 overview of APP automated testing
Laravel+redis generates an order number - automatically increase from 1 on the same day
软件开发中的上游和下游
More pragmatic in business
Machine learning 10 belief Bayesian classifier
聚焦绿色低碳,数据中心散热进入“智能冷却”新时代
如何学习和阅读代码
数学知识:求组合数 III—求组合数
RocketQA:通过跨批次负采样(cross-batch negatives)、去噪的强负例采样(denoised hard negative sampling)与数据增强(data augment
SWT/ANR问题--AMS/WMS
小程序云开发之--微信公众号文章采集篇
Sitge joined the opengauss open source community to jointly promote the ecological development of the database industry
opencv -- 笔记
股票开户有哪些优惠活动?另外,手机开户安全么?