operator overload notes

  1. []Overload
  • For ordinary arrays, the following two writing methods have the same effect:

a[2]
2[a]
Is the third one to access the a array

  • For access to the internal array of the object, only the first method can be used. Here there are two types of return values: numeric and reference. If you want to make a numeric element an lvalue, you must use a reference return value.
// 一维数组访问
int& operator [](int index){
    
    
	if(index > 0 && index < length){
    
    
		return v[index];
	}else{
    
    
		//越界特殊处理
	}
}
// 二维数组访问,这里分行、列来两次访问
int* operator [](int index){
    
    
	if(index > 0 && index < length){
    
    
		// 返回某行指针
		return array[index];
	}else{
    
    
		//越界处理
	}
}
  1. Use operator for type conversion (here are member functions)
  • Class type conversion to standard type
operator int(){
    
    
	//代码块
}
  • Conversion between class types
operator className(){
    
    
	//代码块
}
  • Note: The function has no return value, but you can write the return value inside the code.

Guess you like

Origin blog.csdn.net/weixin_45688536/article/details/106684920