I am getting a error [ error: expected unqualified-id before ‘&’ token ] in a c++ program
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();
开发者_JS百科 cout<<"\n\n";
return 0;
}
You need to tell the compiler that your operator [] function is a member of myArray:
int & myArray::operator [](const int x)
{
return a[x];
}
For more info, this page has decent examples.
The problem is with your definition of the operator []
int myArray & operator [](int x) // This is the line where error is as by compiler
{
return a[x];
}
Should be:
int & myArray::operator [](const int x)
{
return a[x];
}
Also, as an suggestion [] is usually overloaded so as to avoid crossing the array bounds. So your [] overloading should ideally check x
against size
before dereferencing the array at that index. Without such an checking the whole purpose of overloading the [] is defeated.
精彩评论