重载数组下标运算符

#include <iostream>
using namespace std;

class Couple
{
	public:
		//构造函数直接传进参数赋给私有成员数组成员 
		Couple(int a=0,int b=0){_a[0]=a,_a[1]=b;}
		//定义两个操作符函数,传递下表索引
		//第一个是非常量的版本 
		//返回的是int & 也就是数组元素的引用,所以可以通过函数的返回值修改引用所访问的那个目标数据对象
		//引用的当然是对应的那个元素啦 
		int & operator[](int index);
		//下面这个是常函数的版本
		const int & operator[](int index) const;
	private:
		//私有成员是一个整形的数组 
		int _a[2]; 
 }; 
int & Couple::operator[](int index)
{
//	if(index <0||index>1)
//		throw std::out_of_range("Index is out of range!");
	//特别简单,直接返回对应的索引值即可
	return _a[index];
 } 
const int & Couple::operator[](int index) const
{
//	if(index <0||index>1)
//		throw std::out_of_range("Index is out of range!");
	//特别简单,直接返回对应的索引值即可 
	return _a[index];
 } 
 int main()
 {
 	//定义a和b都是类,类里面没有实现数组操作的[]运算符
	 //所以需要重载,直接返回相应的下表值即可 
 	Couple a(1,2),b(3,4);
 	cout<<a[0]<<" "<<a[1]<<endl;
 	cin>>a[0]>>a[1]; 
 	cout<<a[0]<<" "<<a[1]<<endl;
	cout<<b[0]<<" "<<b[1]<<endl;
	return 0;  
 }

猜你喜欢

转载自blog.csdn.net/Li_haiyu/article/details/82082743
今日推荐