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");
}
int operator[](int pos)const;与int& operator[](int pos);的区别
最新推荐文章于 2025-06-13 06:58:40 发布
