当前位置:网站首页>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
}边栏推荐
猜你喜欢

PHP crawls data through third-party plug-ins

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

機器學習10-信念貝葉斯分類器

(翻译)使用眉状文本提高标题点击率

The personal test is effective, and the JMeter desktop shortcut is quickly created

Machine learning 10 belief Bayesian classifier

How to maintain efficient collaboration in remote office and achieve stable growth of projects | community essay solicitation

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

int和位数组互转

How does ZABBIX configure alarm SMS? (alert SMS notification setting process)
随机推荐
Batch import of Excel data in applet
RocketQA:通过跨批次负采样(cross-batch negatives)、去噪的强负例采样(denoised hard negative sampling)与数据增强(data augment
[无线通信基础-14]:图解移动通信技术与应用发展-2-第一代移动模拟通信大哥大
SWT/ANR问题--Binder Stuck
[proteus simulation] Arduino UNO +74c922 keyboard decoding drive 4x4 matrix keyboard
int和位数组互转
对象与对象变量
PHP数组拼接MySQL的in语句
PHP通过第三方插件爬取数据
For the sustainable development of software testing, we must learn to knock code?
工厂+策略模式
How to select securities companies? In addition, is it safe to open a mobile account?
Selenium经典面试题-多窗口切换解决方案
After working for 6 years, let's take stock of the golden rule of the workplace where workers mix up
7-2 拼题A打卡奖励 dp
Handsontable数据网格组件
如何选择券商?另外,手机开户安全么?
软件测试的可持续发展,必须要学会敲代码?
Log4j2 threadcontext log link tracking
远程办公如何保持高效协同,实现项目稳定增长 |社区征文