我收到错误 [ error: Expected unqualified-id before ‘&’ c++ 中的令牌]程序
我收到一个不寻常的错误:
错误:“&”之前应有不合格的 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;
}
I am getting a unusual error:
error: expected unqualified-id before ‘&’ token
Source code:
// 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要告诉编译器您的运算符 [] 函数是 myArray 的成员:
有关详细信息,此页面 有不错的示例。
You need to tell the compiler that your operator [] function is a member of myArray:
For more info, this page has decent examples.
问题在于您对运算符 [] 的定义
应该是:
另外,建议 [] 通常被重载,以避免跨越数组边界。因此,您的 [] 重载理想情况下应该在取消引用该索引处的数组之前检查
x
与size
。如果没有这样的检查,重载 [] 的整个目的就会失败。The problem is with your definition of the
operator []
Should be:
Also, as an suggestion [] is usually overloaded so as to avoid crossing the array bounds. So your [] overloading should ideally check
x
againstsize
before dereferencing the array at that index. Without such an checking the whole purpose of overloading the [] is defeated.