第四周学习:自增、自减运算符重载

前置++/–运算符

成员函数:

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

全局函数

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

后置++/–运算符(多一个没用的参数)

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. 前置返回的是引用,因为前置是先改变值,再作用,就相当于返回一个引用,一个new value;
  2. 后置返回的是value,因为后置是先作用,在改变值,作用的那个其实相当于临时副本,而真正的已经被改变了,所以返回值。
T t(5);
	cout<<(t++)<<", ";
	cout<<t<<", ";
	cout<<(++t)<<", ";
	cout<<t<<endl;
	cout<<(t--)<<", ";
	cout<<t<<", ";
	cout<<(--t)<<", ";
	cout<<t<<endl;

在这里插入图片描述

运算符重载注意:

  1. 不能定义新运算符
  2. 重载后运算符符合日常习惯
  3. 不改变运算符优先级
  4. 不可被重载的:"." 、 “.* “、” :: “、”?:”、“sizeof”
  5. ()、[ ] 、 -> 或 =,必须声明为成员函数

猜你喜欢

转载自blog.csdn.net/ZmJ6666/article/details/108571076