The fourth week of learning: self-increment, self-decrement operator overload

Prefix ++/– operator

Member function:

T& operator--()
T& operator++()

Global function

T1& operator--(T2)
T1& operator++(T2)

Post ++/– operator (one more useless parameter)

T& operator--(int)
T& operator++(int)
T1& operator--(T2,int)
T1& operator++(T2,int)

T operator++(int a){
    
    T tmp(*this); n++; return tmp;}
T& operator++(){
    
    ++n; return *this;}
		
friend T& operator--(T& t,int a);
friend T operator--(T& t);


T& operator--(T& t,int a)
{
    
    
	T tmp(t);
	t.n--;
	return tmp;
}

T operator--(T& t)
{
    
    
	t.n--;
	return t;
}
  1. The front returns a reference, because the front changes the value first and then acts, which is equivalent to returning a reference, a new value;
  2. The post-position returns the value, because the post-position acts first, and when changing the value, the one that acts is actually equivalent to a temporary copy, and the real has been changed, so the value is returned.
T t(5);
	cout<<(t++)<<", ";
	cout<<t<<", ";
	cout<<(++t)<<", ";
	cout<<t<<endl;
	cout<<(t--)<<", ";
	cout<<t<<", ";
	cout<<(--t)<<", ";
	cout<<t<<endl;

Insert picture description here

Note on operator overloading:

  1. Cannot define new operator
  2. Operators conform to daily habits after overloading
  3. Do not change operator precedence
  4. Cannot be overloaded: " . ", ".* ", ":: ", "?:", "sizeof"
  5. (), [], -> or =, must be declared as member functions

Guess you like

Origin blog.csdn.net/ZmJ6666/article/details/108571076