当前位置:网站首页>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
}边栏推荐
- 小程序云开发之--微信公众号文章采集篇
- laravel 事件 & 监听
- org.redisson.client.RedisResponseTimeoutException: Redis server response timeout (3000 ms)错误解决
- Delete duplicate email
- 软件开发中的上游和下游
- CorelDRAW 2022 Chinese Simplified 64 bit direct download
- [无线通信基础-14]:图解移动通信技术与应用发展-2-第一代移动模拟通信大哥大
- With regard to the white box test, you have to master these skills~
- [proteus simulation] Arduino UNO +74c922 keyboard decoding drive 4x4 matrix keyboard
- QT web 开发 - video -- 笔记
猜你喜欢

After working for 6 years, let's take stock of the golden rule of the workplace where workers mix up

SWT/ANR问题--StorageManagerService卡住

Connectivity basis of Graphs

7-2 punch in reward DP for puzzle a
![Pytorch —— 基础指北_贰 高中生都能看懂的[反向传播和梯度下降]](/img/6e/279dbb7a8d7a5ecd240de464c5b8b2.png)
Pytorch —— 基础指北_贰 高中生都能看懂的[反向传播和梯度下降]

3500 word summary: a complete set of skills that a qualified software testing engineer needs to master

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

VirtualBox 安装增强功能

Electron pit Addon

修复表中的名字(首字符大写,其他小写)
随机推荐
45 year old programmer tells you: why do programmers want to change jobs? It's too true
laravel 事件 & 监听
Mathematical knowledge: finding combinatorial number III - finding combinatorial number
PHP crawls data through third-party plug-ins
FL studio20.9 fruit software advanced Chinese edition electronic music arrangement
Composants de la grille de données portatifs
SWT/ANR问题--Dump时间过长导致的SWT
How do the top ten securities firms open accounts? Also, is it safe to open an account online?
How does the property send a text message to the owner?
软件测试的可持续发展,必须要学会敲代码?
Pytorch —— 基础指北_贰 高中生都能看懂的[反向传播和梯度下降]
测试必备工具-Postman实战教程
When facing the industrial Internet, they even use the ways and methods of consuming the Internet to land and practice the industrial Internet
Fast understanding of forward proxy and reverse proxy
For the sustainable development of software testing, we must learn to knock code?
int和位数组互转
How to select securities companies? In addition, is it safe to open a mobile account?
Int and bit group turn to each other
Thinking about business and investment
How to learn and read code