我正在编写一个用于在数组上重载“[]”运算符的程序。这是我的代码
/ / A safe array example.
#include <iostream>
#include <cstdlib>
using namespace std;
class atype {
int a[3];
public:
atype(int i, int j, int k) {
a[0] = i;
a[1] = j;
a[2] = k;
}
int &operator[](int i);
};
// Provide range checking for atype.
int &atype::operator[](int i)
{
if(i<0 || i> 2) {
cout << "Boundary Error\n";
exit(1);
}
return a[i];
}
int main()
{
atype ob(1, 2, 3);
cout << ob[1]; // displays 2
cout << " ";
ob[1] = 25; // [] appears on left
cout << ob[1]; // displays 25
ob[3] = 44; // generates runtime error, 3 out-of-range
return 0;
}
在课堂上,我们声明为
int &operator[](int i);
在类之外它被定义为
int &atype::operator[](int i)
应该是int atype::&operator[](int i)
,但它给了我错误。
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): error C2589: '&' : illegal token on right side of '::'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): warning C4091: '' : ignored on left of 'int' when no variable is declared
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): error C2143: syntax error : missing ';' before '::'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): error C2059: syntax error : '::'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(18): error C2143: syntax error : missing ';' before '{'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(18): error C2447: '{' : missing function header (old-style formal list?)
但是当我尝试int &atype::operator[](int i)
它时,任何人都可以解释一下我们是在传递对类还是运算符的引用 [](int i)