不能在全局范围内使用结构

2021-12-23 00:00:00 struct c++

我在全局范围内定义了 struct,但是当我尝试使用它时,我得到错误:'co' 没有命名类型,但是当我在函数中执行相同操作时,一切工作正常

I defined struct in the global scope, but when I try to use it, I get error: ‘co’ does not name a type, but when I do the same in a function, everything works fine

typedef struct {
  int x;
  int y;
  char t;
} MyStruct;

  MyStruct co;
  co.x = 1;
  co.y = 2;
  co.t = 'a'; //compile error

void f() {
  MyStruct co;
  co.x = 1;
  co.y = 2;
  co.t = 'a';
  cout << co.x << '	' << co.y << '	' << co.t << endl;
} //everything appears to work fine, no compile errors

我做错了什么,还是结构不能在全局范围内使用?

Am I doing something wrong, or structures just cannot be used in global scope?

推荐答案

并不是说您不能在全局范围内使用结构".这里的结构没有什么特别之处.

It's not that you "can't use structures in global scope". There is nothing special here about structures.

您根本无法编写程序代码,例如函数体之外的赋值.任何对象就是这种情况:

You simply cannot write procedural code such as assignments outside of a function body. This is the case with any object:

int x = 0;
x = 5; // ERROR!

int main() {}

此外,向后 typedef 是上个世纪的废话(在 C++ 中不需要).

Also, that backwards typedef nonsense is so last century (and not required in C++).

如果您要初始化对象,请执行以下操作:

If you're trying to initialise your object, do this:

#include <iostream>

struct MyStruct
{
   int x;
   int y;
   char t;
};

MyStruct co = { 1, 2, 'a' };

int main()
{
   std::cout << co.x << '	' << co.y << '	' << co.t << std::endl;
}

相关文章