2011-04-03 40 views
1

我得到一个不寻常的错误:我得到一个错误[错误:前 '和' 令牌预期不合格-ID]在C++程序

error: expected unqualified-id before ‘&’ token

源代码:

// 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; 
} 
+0

您正确定义了您的'print_array'方法,这意味着您熟悉方法定义的C++语法。然而,'operator []'定义中的语法完全搞砸了,变成了无意义的标记序列。这怎么可能? – AnT 2011-04-03 06:02:41

+0

我正在学习操作符重载的概念,并且我也尝试了以下建议的方式,但没有成功 – 2011-04-03 06:33:53

回答

1

你需要告诉编译器,你的operator []的功能是myArray的成员:

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

欲了解更多信息,this page有体面的例子。

+0

在完成上述操作后,我得到很多错误:[link](cl.ly/5hUN) – 2011-04-03 06:20:49

+0

编译C++代码用'g ++',而不是'gcc'。并开启警告!在'g ++'参数中添加'-Wall'。 – Mat 2011-04-03 06:59:46

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。没有这样的检查,重载[]的全部目的就会被击败。

+0

“没有这样的检查,重载[]的全部目的就被击败了。” - 不,不是。重载它的目的是提供一个类似数组的接口,而不是检查边界。尽管这当然是一件正确的事情。 – Xeo 2011-04-03 06:12:24

+0

做完上述后,我得到了很多错误:[链接](http://cl.ly/5hUN) – 2011-04-03 06:17:50

+0

@Xeo:一个数组像接口没有边界检查,这是什么使用? – 2011-04-03 06:33:11

相关问题