我有一个名为Grid.h的类头文件,其中包含以下2个私有数据对象:
vector<int> column;
vector<vector<int>> row;
Run Code Online (Sandbox Code Playgroud)
一个公共方法,其原型在Grid.h中是这样的:
int getElement (unsigned int& col, unsigned int& row);
Run Code Online (Sandbox Code Playgroud)
上面提到的函数的定义在Grid.cpp中定义如下:
int getElement (unsigned int& col, unsigned int& row)
{
return row[row][col] ;
}
Run Code Online (Sandbox Code Playgroud)
当我运行该程序时,我收到此错误:
error C2109: subscript requires array or pointer type
Run Code Online (Sandbox Code Playgroud)
什么出错了?
Jon*_*vis 18
在return row[row][col];第一行row是int&,而不是vector.
在内部作用域中声明的变量是在外部作用域中隐藏变量,因此编译器正在尝试索引int而不是a vector,这显然是不能做的.
您应该修改变量名称,以便它们不会发生冲突.
编辑:此外,虽然你得到的错误表明编译器找到了错误的row变量,正如A. Levy指出的那样,你的声明也有问题vector,所以即使你修改了变量名,如果你确实声明了vector这里显示的,它不会编译.嵌套模板需要>符号之间的空格,否则编译器将读>>作右移运算符而不是模板声明的一部分.它需要
std::vector<std::vector<int> > row;
Run Code Online (Sandbox Code Playgroud)
要么
std::vector< std::vector<int> > row;
Run Code Online (Sandbox Code Playgroud)
另外,当您在头文件中执行此操作时,您将需要std::在std命名空间的前面添加标记 - 例如vector.如果它在cpp文件中,那么你可以使用using namespace std;但在头文件中这样做会非常糟糕(因为它会污染全局命名空间).如果没有std::标记或using语句,编译器将无法识别vector.
这可能不是索引问题,但您还需要向量类型声明向量中的嵌套尖括号之间的空格.C++编译器很难说明嵌套模板类型和正确的位移运算符之间的区别.
例:
vector<vector<int> > vec2d; // Good.
vector<vector<int>> anotherVec2d; // Bad!
vector< vector<int> > yetAgain; // Best IMHO.
// Keeps the white space balanced.
Run Code Online (Sandbox Code Playgroud)