Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

c++ - can't use structure in global scope

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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() {}

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...