1

我收到一个不寻常的错误:

错误:“&”之前的预期不合格 ID 令牌

源代码:

// Overloading the c++ array subscript operator [ ]

#include<iostream>
using namespace std;

const int size=10;

class myArray
{
      int a[size];
    public:
      myArray()
      {}
      int & operator [](int);
      void print_array();   
};

int myArray & operator [](int x) // This is the line where error is as by compiler
{
          return a[x];
}

void myArray::print_array()
{
    for (int j=0; j < 10; j++)
        cout<<"array["<<j<<"] = "<<a[j]<<"\n";
}

int main()
{
    myArray instance;
    for (int i=0; i < size; i++)
     {
       instance[i] = i;
     }  
    instance.print_array();

    cout<<"\n\n";
    return 0;
}
4

2 回答 2

1

您需要告诉编译器您的 operator [] 函数是 myArray 的成员:

int & myArray::operator [](const int x) 
{
          return a[x];
}

有关更多信息,此页面有不错的示例。

于 2011-04-03T04:40:15.050 回答
0

问题在于您对operator []

int myArray & operator [](int x) // This is the line where error is as by compiler
{
          return a[x];
}

应该:

int & myArray::operator [](const int x) 
{
          return a[x];
}

此外,作为建议 [] 通常被重载以避免跨越数组边界。因此,理想情况下,您的 [] 重载应该xsize取消引用该索引处的数组之前进行检查。如果没有这样的检查,重载 [] 的整个目的就会失败。

于 2011-04-03T05:45:22.063 回答