【问题标题】:I am getting a error [ error: expected unqualified-id before ‘&’ token ] in a c++ program我在 C++ 程序中收到错误 [错误:在“&”标记之前预期的不合格 ID]
【发布时间】:2011-04-06 02:51:49
【问题描述】:

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

错误:'&' 标记之前的预期 unqualified-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;
}

【问题讨论】:

  • 您正确定义了print_array 方法,这意味着您熟悉方法定义的C++ 语法。然而,operator [] 定义中的语法被完全搞砸了,以至于变成了毫无意义的标记序列。这怎么可能?
  • 我正在学习运算符重载的概念,我也尝试了下面推荐的方法,但没有成功

标签: c++ operator-keyword subscript


【解决方案1】:

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

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

如需更多信息,this page 提供了不错的示例。

【讨论】:

  • 执行上述操作后,我收到很多错误:[link] (cl.ly/5hUN)
  • g++ 编译C++ 代码,而不是gcc。并打开警告!在g++参数中添加-Wall
【解决方案2】:

问题在于您对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。如果没有这样的检查,重载 [] 的整个目的就会失败。

【讨论】:

  • “如果没有这样的检查,重载 [] 的整个目的就失败了。” ——不,不是。重载它的目的是提供一个类似数组的接口,而不是检查边界。虽然这当然是正确的做法。
  • @Xeo:类似数组的接口,没有边界检查,有什么用?
  • @Samrat Mazumdar:您正在使用 gcc 编译 C++ 源代码。使用g++,它会正确编译。您可以使用g++ 来编译 C 和 C++ 源代码,大多数情况下它会很好,但反之则不然。这是一个带有上述修改的键盘链接,codepad.org/sOLpXE35,它可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多