当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Why can't I add to a ostringstream outside a method/function

问题描述:

If I use this code outside of a method or winmain:

ostringstream vertexid;

vertexid << "bob";

vertexid << " ";

vertexid << " ";

vertexid << 48348093490;

I get all sorts of syntax errors. How does scope play into this why is this happening?

网友答案:

You can do something like this:

std::ostringstream ss;

#define nil(x) ((x), 0)
int x = nil(ss << "Hello");
int y = nil(ss << ", World!");
int z = nil(ss << std::endl);

If you really don't like thinking up variable names, then you can do something even crazier:

#define nilPASTE(x, y) x ## y
#define nilPASTE2(x, y) nilPASTE(x, y)
#define nil2(x) static int nilPASTE2(line_, __LINE__) = nil(x)
nil2(ss << "Goodbye");
nil2(ss << ", Sun!");
nil2(ss << std::endl);

You asked:

How does scope play into this why is this happening?

I assume you mention scope because that is what some error message spat out. But the answer to both parts of that question is that the C++ compiler is following the rules of the C++ language, which does not allow statements to just appear anywhere. They can only appear where they are allowed, which are in functions and method bodies. The reason my technique is allowed is because I am using expressions, and expressions can appear in more places. In particular, they are allowed to appear in an initializer to a variable. And of course, variable declarations are allowed on the outer most level of a translation unit.

All that gobbly gook means: put your statements inside functions and methods.

网友答案:

You can only declare or define stuff at global scope.

The first line alone would be OK (in an implementation file... if in a header, you risk having multiple definitions and would need to declare it as extern instead of defining it), the next lines are just not legal.

网友答案:

At global namespace you cannot have code, because when should it be executed? You can only put executable statements inside functions, for example WinMain/main.

The execution starts at WinMain/main, then you can call your other functions from there.

分享给朋友:
您可能感兴趣的文章:
随机阅读: