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;
}
- 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;
- 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;
Note on operator overloading:
- Cannot define new operator
- Operators conform to daily habits after overloading
- Do not change operator precedence
- Cannot be overloaded: " . ", ".* ", ":: ", "?:", "sizeof"
- (), [], -> or =, must be declared as member functions