operator重载笔记

  1. [ ]重载
  • 对于普通数组,下列两种写法效果是一样的:

a[2]
2[a]
都是访问a数组的第三个

  • 对于访问对象内部的数组,只能用第一种写法。在这里返回值类型有数值、引用两种,如果要使数值元素做左值,必须用引用返回值。
// 一维数组访问
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. 利用operator 进行类型转换(这里都是成员函数)
  • 类类型转换成标准类型
operator int(){
    
    
	//代码块
}
  • 类类型之间相互转换
operator className(){
    
    
	//代码块
}
  • 注意:函数没有返回值,但是可以在代码内部写返回值。

猜你喜欢

转载自blog.csdn.net/weixin_45688536/article/details/106684920