【发布时间】:2021-01-06 02:13:04
【问题描述】:
这是我得到的错误:
'global_grid' was not declared in this scope
Notator 类中的这一行(定义如下)导致错误:
int option = global_grid.GetOption();.
Director 正在协调与网格一起工作的不同模块。我需要一个网格可供所有班级使用。我不希望它是一个单例,因为可以想象有多个网格。我不希望它属于Director 类,因为这在概念上对我来说没有意义。 Director 只是引导流量。
我认为global_grid(如下声明)会随处可见。我想我不明白static,或者可能是如何访问该对象。
没有导致错误的语句,项目编译。我错过了什么?
class SoundFile // This module has a grid that is needed by the other modules
{
public:
int GetOption(){ return 0; }
};
class Director // Coordinates communication between modules
{
public:
SoundFile& CreateGrid()
{
static SoundFile grid; // All modules need access to this grid.
return grid;
}
void SetUp() // I want to call this when the app starts, to
//create a global grid.
{
SoundFile& global_grid = CreateGrid(); // Would this create a static object?
}
};
class Notator // One of the modules that needs access to the grid
{
public:
void Work()
{
int option = global_grid.GetOption(); // Causes the error
}
};
【问题讨论】:
-
好的,让我看看链接上的信息
-
global_grid是Director::SetUp中的本地标识符 -
错误信息指的是
global_grid。为什么你认为global_grid是静态的?您使用static关键字的唯一声明是grid。 -
实际上,这整个“静态”业务与您的错误无关。 (“静态”并不意味着“全局”。)再次阅读错误消息:“在此范围内声明”。为什么你认为
global_grid(在Director::SetUp()内本地声明)是在发生错误的范围内声明的?