G ++"没有命名类型"

tre*_*ree 1 c++ global

struct MyStruct {
  int x;
};

MyStruct theVar;

theVar.x = 10;

int main() {
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么编译器会给我错误:

错误:'theVar'没有命名类型

Alo*_*ave 6

您只能main在全局范围内创建变量并将其初始化.您不能像这样在全局范围内分配变量.

您有两种选择:

在创建时初始化它:

MyStruct theVar = {10};
Run Code Online (Sandbox Code Playgroud)

要么

分配给main:

theVar.x = 10;
Run Code Online (Sandbox Code Playgroud)

请注意,第一种方法更好,因为它只有一步,初始化,第二步有两步初始化分配.