int operator[](int pos)const;与int& operator[](int pos);的区别

本文介绍了C++中下标运算符两种重载方式的区别:返回引用和返回值。通过具体示例展示了如何实现这两种重载,并解释了它们在不同场景下的应用。
int operator[](int pos)const;与int& operator[](int pos);的区别
搜索反回类型为引用的下标运算符一般在使用时用作左值,比如c[1]=1;在这种情况下,必须要求c[1]的结果是一个可以赋值的左值,因此int& operator[](int pos);这个函数的版本主要是为左值设定的,反回对变量的引用就可以作为左值。

int operator[](int pos)const;这个版本要注意,const一定要在后面,表示这个函数不能修改修改类中的变量,同时写在后面也表示这是前一个函数int& operator[](int pos);的重载版本,这样在调用语句比如c[1]时就不会出现二义性错误。这个版本的函数主要是用于下标运算符作为右值时使用的,但一般情况下用不到,比如b=a[1];这时同样是调用的int& operator[](int pos);版本的函数,除非变量c是const类型的。

在你给出的示例中,重写这两个函数都很简单,只需return p_arr[pos]即可,或者在反回之前加上对数组下标的边界检查就行了。下面举个用法

// ggg.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

class CArray
{
private:
int *p_arr;
int size;
public:
CArray()
{ 
int a[3]={111,222,333};
p_arr=new int[3];
for(int i=0;i<3;i++) 
p_arr[i]=a[i];
size=3;
}

int operator[](int pos)const;//访问数组元素值的下标运算符重载函数

int& operator[](int pos) ; //设置数组元素值的下标运算符重载函数
};

int CArray::operator[](int pos)const {

cout<<"A"<<endl; 
if(pos<0 || pos>=size){
cout <<"Error!\n";
exit(1);
}
return p_arr[pos];

}

int& CArray::operator[](int pos){
cout<<"B"<<endl;

if(pos<0 || pos>=size){
cout <<"Error!\n";
exit(1);
}
return p_arr[pos];

}

void main()
{ int a=1;
CArray c;
const CArray b;

/*以下两个语句都会调用int& CArray::operator[](int pos)版本的重载函数*/
c[1]=2; /*这里会输出B */
a=c[1]; /*这里会输出B,说明调用的是第int &CArray::operator[](int pos)版本的函数 */

/*以下语句会调用int CArray::operator[](int pos)const 版本的重载函数*/

a=b[1]; /*这里会输出A,说明调用的是第int CArray::operator[](int pos)const版本的函数 */

cout<<c[0]<<endl; /*这里输出B之后输出111,因为使用了[]运算符,所以会调用重载的下标运算符函数*/
cout<<c[1]<<endl; /*这里输出B之后输出2,因为使用了[]运算符,所以会调用重载的下标运算符函数*/
cout<<a<<endl;
system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值