C++新手.在下面的程序中我写的是我收到此错误:
g++ -o Blob blob.cc blob.cc: In function 'int nonrecursivecountcells(color (*)[7], int, int)': blob.cc:41: error: 'grid' was not declared in this scope
这是代码:
#includeenum color {BACKGROUND, ABNORMAL, TEMPORARY}; const int ROW_SIZE = 7; const int COL_SIZE = 7; int nonrecursivecountcells(color[ROW_SIZE][COL_SIZE], int, int); using namespace std; int main() { color grid[ROW_SIZE][COL_SIZE] = {{BACKGROUND, ABNORMAL, BACKGROUND, ABNORMAL, BACKGROUND, BACKGROUND, BACKGROUND}, {ABNORMAL, ABNORMAL, BACKGROUND, ABNORMAL, BACKGROUND, BACKGROUND, BACKGROUND}, {BACKGROUND, BACKGROUND, ABNORMAL, ABNORMAL, BACKGROUND, BACKGROUND, ABNORMAL}, {BACKGROUND, BACKGROUND, BACKGROUND, ABNORMAL, ABNORMAL, ABNORMAL, BACKGROUND}, {BACKGROUND, BACKGROUND, BACKGROUND, ABNORMAL, BACKGROUND, BACKGROUND, BACKGROUND}, {BACKGROUND, BACKGROUND, BACKGROUND, BACKGROUND, BACKGROUND, ABNORMAL, BACKGROUND}, {BACKGROUND, ABNORMAL, ABNORMAL, BACKGROUND, BACKGROUND, BACKGROUND, ABNORMAL}}; cout << "Enter row number" << endl; int row; cin >> row; cout << "Enter column number" << endl; int column; cin >> column; int number = nonrecursivecountcells(grid, row, column); cout << "Number off cells in the blob that contains grid[" << row << "][" << column << "] are: " << number << endl; return 0; } int nonrecursivecountcells(color[ROW_SIZE][COL_SIZE], int row, int column) { if (row < 0 || row >= ROW_SIZE || column < 0 || column >= COL_SIZE) { return 0; } else if (grid[row][column] != ABNORMAL) { return 0; } else { grid[row][column] = TEMPORARY; return 1 + nonrecursivecountcells(grid, row - 1, column - 1) + nonrecursivecountcells(grid, row - 1, column) + nonrecursivecountcells(grid, row - 1, column + 1) + nonrecursivecountcells(grid, row, column + 1) + nonrecursivecountcells(grid, row + 1, column + 1) + nonrecursivecountcells(grid, row + 1, column) + nonrecursivecountcells(grid, row + 1, column - 1) + nonrecursivecountcells(grid, row, column - 1); } }
有人可以帮我从这里出去吗?谢谢.
怎么了:
"nonrecursivecountcells"的定义没有名为grid的参数.您需要将类型AND变量名称传递给函数.你只传递了这种类型.
请注意,如果对参数使用名称网格,则该名称与网格的main()声明无关.您也可以使用任何其他名称.
***
您也无法将数组作为值传递.
怎么修:
解决这个问题的简单方法是将指向数组的指针传递给函数"nonrecursivecountcells".
int nonrecursivecountcells(color[ROW_SIZE][COL_SIZE], int, int);
更好,类型安全 - >
int nonrecursivecountcells(color (&grid)[ROW_SIZE][COL_SIZE], int, int);
关于范围:
当声明它的块终止时,在堆栈上创建的变量超出范围.块是开放和匹配的右括号内的任何东西.例如if(){},function(){},while(){},...
注意我说变量而不是数据.例如,您可以在堆上分配内存,即使在范围之外,该数据仍将保持有效.但最初指向它的变量仍然会超出范围.