C++ classes and objects (5)

1. Operator overloading for stream insertion and stream extraction

insert image description here
Operator overloading of stream insertion operators and stream extraction operators is possible through function overloading. <<stream insertion is in ostream, >>stream extraction is in istream.

① The operator overloading of stream extraction and stream insertion is not recommended to be written as a member function; it should be written as a global function
insert image description here
② In order to access the member variables of the class, it can be declared as a friend function in the class, keyword: friend
insert image description here
insert image description here
③ In order to implement multiple times in one line, the function Value returns the corresponding type, stream insertion return type: ostream&; stream extraction return type: istream&
insert image description here

2. const members

The const-modified "member function" is called a const member function. The const-modified class member function actually modifies the implicit this pointer of the member function, indicating that any member of the class cannot be modified in the member function.
insert image description here
insert image description here
insert image description here
insert image description here

3. Address and const address operator overloading

These two default member functions generally do not need to be redefined, and the compiler will generate them by default.

class Date
{
    
    
public:
	Date* operator&()
	{
    
    
		return this;
	}
	const Date* operator&()const
	{
    
    
		return this;
	}
private:
	int _year; // 年
	int _month; // 月
	int _day; // 日
};

These two operators generally do not need to be overloaded, just use the default address overload generated by the compiler. Only in special cases, overloading is required, such as wanting others to obtain the specified content!

Guess you like

Origin blog.csdn.net/zxj20041003/article/details/130516452