Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...