gpt4 book ai didi

C++ "was not declared in this scope"编译错误

转载 作者:可可西里 更新时间:2023-11-01 15:40:40 25 4
gpt4 key购买 nike

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

代码如下:

#include <iostream>
enum 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 的参数。您需要将类型和变量名传递给函数。你只传递了类型。

请注意,如果您使用名称 grid 作为参数,则该名称与 grid 的 main() 声明无关。您也可以使用任何其他名称。

***Also you can't pass arrays as values.


如何修复:

解决此问题的简单方法是将指向数组的指针传递给函数“nonrecursivecountcells”。

int nonrecursivecountcells(color[ROW_SIZE][COL_SIZE], int, int);

更好并且类型安全 ->

int nonrecursivecountcells(color (&grid)[ROW_SIZE][COL_SIZE], int, int);

关于范围:

当声明它的 block 终止时,在堆栈上创建的变量超出范围。 block 是位于左括号和匹配 右括号内的任何内容。例如 if() { }, function() { }, while() {}, ...

注意我说的是变量而不是数据。例如,您可以在堆上分配内存,即使在范围之外,该数据仍然有效。但是最初指向它的变量仍然会超出范围。

关于C++ "was not declared in this scope"编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/674448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com