【发布时间】: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