重载[]操作符基础

Overload [] operator basics

本文关键字:操作符 重载      更新时间:2023-10-16

我做了这个例子来理解[]运算符的使用,但是这个代码给了我一个错误"将操作符声明为函数数组","在示例[0]中没有匹配操作符[]"以及类似的不同错误。请告诉我做错了什么,请解释一下。提前感谢

#include <iostream>
using namespace std;
class example
{ 
private:
        double temp[8];
public:
    example () 
    {  
          temp[0] = 3.5; temp[1] = 3.2;  temp[2] = 4;    temp[3] = 3.3; 
          temp[4] = 3.8; temp[5] = 3.6;  temp[6] = 3.5; temp[7] = 3.8;
    }

    double& opeator[] (int Index);
};
double& example::operator[](int Index)
{       
        return temp[Index];        
}

int main ()
{
    example Example;
    Example[0] = 4;
    double temp = Example[4];
}

This:

double& opeator[] (int Index);

应该是:

double& operator[] (int Index);
//         ^

还请我没有正确理解[]运算符的用法,很清楚,还请稍微解释一下。我读了这篇文章,并做了这个例子来理解,但在理解上仍然有问题。

嗯,operator[]对于模拟数组索引行为特别有用。标准库在"类数组"类(如std::vectorstd::deque)上使用此操作符。

你的例子(除了明显的类型):

double& example::operator[](int Index) {       
        return temp[Index];        
}

是运算符的完美应用。我唯一建议您更改的是Index的类型:它实际上应该是std::size_t

有关操作符重载的更多信息,请参见此问题