C++: Operator overloading and assignment operator overloading functions of classes

Table of contents

Chapter knowledge structure

1. Operator overloading

1. The basic concept of operator overloading

    code snippet 1

2. Important grammatical rules about operator overloading

2. The use of operator overloading in classes

3. The default member function of the class: = overloaded function (assignment operator overloaded) 

1. Custom = overloaded function

   code snippet 2

2. = Overloaded function generated by the compiler by default 

Four. Overloading of front ++(--) and post ++(--)


Chapter knowledge structure

                                                    

1. Operator overloading

C++ introduces operator overloading to enhance the readability of the code . Operator overloading is a function with a special function name

1. The basic concept of operator overloading

The keyword that defines operator overloading in C++: operator 

  1. Operator overloading is essentially a function , with a return value type, function name and parameter list, and its return value type and parameter list are similar to ordinary function definition rules;
  2. The function name naming rules of operator overloading function : keyword operator + operator symbol that needs to be overloaded (for example, define the function name operator> , which means operator overloading of > );
  3. The number of formal parameters of an operator overloaded function must be the same as the number of overloaded operators : the overloaded function of a unary operator has one and only one formal parameter , and the overloaded function of a binary operator has and only two formal parameters .
  4. Operator overloaded functions must have a class type parameter
  5. The general form of the operator overloaded function header: return value type + operator operator + (parameter list);

for example:

Now there is a class Date that records dates , and we want to compare the date sizes recorded by two date objects , so we design an overloaded function for the operator '>' .

The return type of the function is defined as bool; bool is a one-byte integer, which can only be true (value 1) or false (value 0)

The function name is defined as: operator>

The formal parameter table of the function is: (const Date & date2 , const Date & date2)

code snippet 1

#include <iostream>

using std::cout;
using std::cin;
using std::endl;





class Date         记录日期的类
{                    
public:
	Date(int day = 0, int month = 0,int year = 0)          Date的带参构造函数
	{
		_day = day;
		_month = month;
		_year = year;
	}

	int _day;
	int _month;
	int _year;
};

bool operator> (const Date& date1, const Date& date2)       将 > 运算符进行重载用于日期比较
{
	if (date1._year > date2._year)
	{
		return true;
	}
	else if (date1._year == date2._year && date1._month > date2._month)
	{
		return true;
	}
	else if (date1._year == date2._year && date1._month == date2._month && date1._day >                 
    date1._day)
	{
		return true;
	}
	return false;
}



int main()
{
	Date a(2021, 4, 23);
	Date b(2022, 1, 27);

	if (a > b)                      用运算符重载来比较两个日期对象
	{
		cout << "Date a > Date b" << endl;
	}
	else
	{
		cout << "Date a < Date b" << endl;
	}
	return 0;
}

C++ compilation will judge whether the operator needs to call overloading and which form of overloading to call according to the type of the operand of the operator , such as the a>b expression in the main function of the above code segment:

2. Important grammatical rules about operator overloading

  • New operators cannot be created by concatenating other symbols: e.g. operator@
  • When a function is overloaded as a class member operator , the number of formal parameters seems to be 1 less than the number of operators , because the first parameter of a class member function is a hidden this pointer; about this pointer: http://t.csdn. cn/hncvq
  • Assignment operator overloading (such as =, +=, -+, *=, etc.) can only be used as a member function of a class and cannot be overloaded as a global function
  • '".* " "::" "sizeof" "?:" "." Note that the above 5 operators cannot be overloaded.

2. The use of operator overloading in classes

  • C++ introduces operator overloading to improve the readability of the code, allowing us to construct operational expressions between complex class objects.
  • Operator overloading must have a class type parameter , so in the operator overloading function we inevitably have to access the member variables of the class
  • In order to ensure encapsulation, the member variables of a class are often defined in the private domain .
  • Therefore, in order to ensure the encapsulation of the class object and allow the operator overloading function to directly access the member variables of the class , in most cases, we often define the operator overloading function as a member function (method) of the class .

Now optimize code segment 1:

Define operator overloading functions as member functions (methods) of classes

Be careful not to ignore the this pointer when the operator overloading function is defined as a member function of the class

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

class Date         //记录日期的类
{
public:
	Date(int day = 0, int month = 0,int year = 0)
	{
		_day = day;
		_month = month;
		_year = year;
	}

	bool operator> (const Date& date)       //将 > 运算符进行重载
	{
		if (_year > date._year)
		{
			return true;
		}
		else if (_year == date._year &&_month > date._month)
		{
			return true;
		}
		else if (_year == date._year && _month == date._month && _day > date._day)
		{
			return true;
		}
		return false;
	}
	
private:
	int _day;
	int _month;
	int _year;
};



int main()
{
	Date a(29, 4, 2020);
	Date b(27, 4, 2020);

	if (a > b)
	{
		cout << "Date a > Date b" << endl;
	}
	else
	{
		cout << "Date a < Date b" << endl;
	}
	return 0;
}

 

 

Simply observe the assembly instructions for the a>b expression:

3. The default member function of the class: = overloaded function (assignment operator overloaded) 

There is an overload of the assignment operator = in the default member function of the class :

If we do not customize an overload of the assignment operator = in the class, the compiler will automatically generate a default = operator overload function in the class .

1. Custom = overloaded function

The assignment operator (=) can only be overloaded as a member function of a class and cannot be overloaded as a global function

  • Reason: If the assignment operator is not defined by us, the compiler will generate a default assignment operator overload in the class (in any class) . At this time, if we define a global assignment operator overload outside the class domain , it will conflict with the default assignment operator overload generated by the compiler in the class , so the assignment operator overload can only be a member function of the class.

Custom = overloaded function:

Now implement an = overloaded function in the Date class: If we customize the = overloaded function in the class , the compiler will not automatically generate its default assignment operator (=) overload during the compilation phase .

code snippet 2

using std::cout;
using std::cin;
using std::endl;





class Date         记录日期的类
{
public:
	Date(int day = 0, int month = 0,int year = 0)
	{
		_day = day;
		_month = month;
		_year = year;
	}

	bool operator> (const Date& date)       将 > 运算符进行重载
	{
		if (_year > date._year)
		{
			return true;
		}
		else if (_year == date._year &&_month > date._month)
		{
			return true;
		}
		else if (_year == date._year && _month == date._month && _day > date._day)
		{
			return true;
		}
		return false;
	}
	
	Date& operator=(const Date& date)        将 = 运算符进行重载
	{
		_day = date._day;
		_month = date._month;
		_year = date._year;
		return (*this);
	}

private:
	int _day;
	int _month;
	int _year;
};



int main()
{
	Date a(29, 4, 2020);
	Date b;
	Date c;

	c = b = a;                              用=的重载完成连续赋值

	if (a > b)
	{
		cout << "Date a > Date b" << endl;
	}
	else 
	{
		cout << "Date a <= Date b" << endl;
	}
	return 0;
}

You can try to observe the assembly instruction of c=b=a in the code segment:

Note: = Overloaded functions use reference parameter passing and reference return instead of value passing parameter and value return in order to improve the running efficiency of the code ( the value passing needs to copy out the temporary class object )

See: http://t.csdn.cn/Rc5aI

           http://t.csdn.cn/9tLyK

2. = Overloaded function generated by the compiler by default 

The = overloaded function generated by the compiler by default:

The function of the = operator overloaded function generated by the compiler by default is similar to that of the custom = overloaded function in Code Segment 2 :

It can be easily verified:

Comment out the code segment overloaded with the equal sign in code segment 2

using std::cout;
using std::cin;
using std::endl;




class Date         //记录日期的类
{
public:
	Date(int day = 0, int month = 0,int year = 0)
	{
		_day = day;
		_month = month;
		_year = year;
	}

	bool operator> (const Date& date)       //将 > 运算符进行重载
	{
		if (_year > date._year)
		{
			return true;
		}
		else if (_year == date._year &&_month > date._month)
		{
			return true;
		}
		else if (_year == date._year && _month == date._month && _day > date._day)
		{
			return true;
		}
		return false;
	}
	
	//Date& operator=(const Date& date)     //将等号重载的代码段注释掉
	//{
	//	if (this != &date)
	//	{
	//		_day = date._day;
	//		_month = date._month;
	//		_year = date._year;
	//	}

	//	return (*this);
	//}

private:
	int _day;
	int _month;
	int _year;
};



int main()
{
	Date a(29, 4, 2020);
	Date b;
	Date c;

	c = b = a;

	if (a > b)
	{
		cout << "Date a > Date b" << endl;
	}
	else 
	{
		cout << "Date a <= Date b" << endl;
	}
	return 0;
}

If there is a class object member variable in the class , the = overloaded function generated by the default compiler of this class will call the assignment operator overload of its member class object

for example:

using std::cout;
using std::cin;
using std::endl;


class subclass                        //定义一个被嵌套的类
{
public:
	subclass(int a = 100)             定义subclass的构造函数
	{
		_a = 100;
	}
	subclass& operator = (const subclass& date)       定义subclass的赋值运算符重载函数
	{
		_a = date._a;
		cout << "hello" << endl;                      打印一下表示该函数被调用
		return (*this);
	}
private:

	int _a;
};

class Date         //记录日期的类
{
public:
	Date(int day = 0, int month = 0,int year = 0,int subclass=0)
	{
		_day = day;
		_month = month;
		_year = year;
	}

	//bool operator> (const Date& date)       //将 > 运算符进行重载
	//{
	//	if (_year > date._year)
	//	{
	//		return true;
	//	}
	//	else if (_year == date._year &&_month > date._month)
	//	{
	//		return true;
	//	}
	//	else if (_year == date._year && _month == date._month && _day > date._day)
	//	{
	//		return true;
	//	}
	//	return false;
	//}
	
	//Date& operator=(const Date& date)     //将等号重载的代码段注释掉
	//{
	//	if (this != &date)
	//	{
	//		_day = date._day;
	//		_month = date._month;
	//		_year = date._year;
	//	}

	//	return (*this);
	//}

private:
	int _day;
	int _month;
	int _year;
	subclass _subdate;
};



int main()
{
	Date a(29, 4, 2020,100);
	Date b;
	Date c;

	c = b = a;

	//if (a > b)
	//{
	//	cout << "Date a > Date b" << endl;
	//}
	//else 
	//{
	//	cout << "Date a <= Date b" << endl;
	//}
	return 0;
}

This process can be observed through assembly instructions:

  • It should be noted that: similar to the copy constructor , the default assignment operator overload generated by the compiler in the class is to complete the class object assignment by copying byte by byte (this copy method is called shallow copy). 
  • Therefore, the assignment operator overload generated by the compiler by default cannot be used for copy assignment between some objects that have applied for additional memory resources . (such as copy assignment between stack objects)

If the = overloaded function generated by the compiler by default is used between stack objects, the following situations will occur:

Therefore, the user-defined = overload can only be used to complete deep copy between class objects related to memory resource management .

Four. Overloading of front ++(--) and post ++(--)

 For the Date class, let's implement the ++ overload indicating that the date is incremented (the date is increased by one day)

using std::cout;
using std::cin;
using std::endl;


//class subclass                        //定义一个被嵌套的类
//{
//public:
//	subclass(int a = 100)             //定义subclass的构造函数
//	{
//		_a = 100;
//	}
//	subclass& operator = (const subclass& date)       //定义subclass的赋值运算符重载函数
//	{
//		_a = date._a;
//		cout << "hello" << endl;                      //打印一下表示该函数被调用
//		return (*this);
//	}
//private:
//
//	int _a;
//};

class Date         //记录日期的类
{
public:
	Date(int day = 0, int month = 0, int year = 0)   //Date的构造函数
	{
		_day = day;
		_month = month;
		_year = year;
	}

	//bool operator> (const Date& date)       //将 > 运算符进行重载
	//{
	//	if (_year > date._year)
	//	{
	//		return true;
	//	}
	//	else if (_year == date._year &&_month > date._month)
	//	{
	//		return true;
	//	}
	//	else if (_year == date._year && _month == date._month && _day > date._day)
	//	{
	//		return true;
	//	}
	//	return false;
	//}

	//Date& operator=(const Date& date)     
	//{
	//	if (this != &date)
	//	{
	//		_day = date._day;
	//		_month = date._month;
	//		_year = date._year;
	//	}

	//	return (*this);
	//}
	Date& operator++()             //实现日期类的前置++
	{
		_day++;
		return (*this);
	}

	Date operator++(int)           //实现日期类的后置++
	{
		Date tem(*this);
		_day++;
		return tem;
	}

	void Print()                    //类对象的日期打印函数
	{
		cout << _year << ' ' << _month << ' ' << _day << ' ' << endl;
	}

private:
	int _day;
	int _month;
	int _year;

};



int main()
{
	Date a(5, 4, 2020);
	a.Print();
	Date ret1(a++);
	ret1.Print();
	Date ret2(++a);
	ret2.Print();
	return 0;
}

Code illustration:

Note a grammar rule:

The pre-- and post-- overloads are similar to ++.

Guess you like

Origin blog.csdn.net/weixin_73470348/article/details/128754747