can we make global variables by defining a class v

2019-09-29 06:48发布

class abc
{
    public:
    int x;
};

abc b1;

b1.x=10;

int main()
{

}

why can't we write this b1.x=10; outside of the main function? it shows error if we write b1.x=10; outside of the main function, why?

5条回答
地球回转人心会变
2楼-- · 2019-09-29 07:31

You're trying to put procedural statements outside any function; it's not allowed. There are two reasons this could be confusing:

1) Maybe you're used to languages where you can have code outside any function. In perl, for example, the whole file is a script that gets executed, and defining and calling functions is entirely a matter of choice. Not so in C++; statements to execute go in functions.

2) b1.x=10 may resemble a declaration, which indeed could go outside any function. But it's not. It is a statement. By contrast outside a function saying int x=10 is a definition (a type of declaration, which happens to include an initializer that looks very much like the assignment expression statement).

查看更多
Melony?
3楼-- · 2019-09-29 07:32

What you're doing is an assignment to a variable. That can't be done outside of a function.

What you can do is initialize that variable at the time it is declared.

abc b1 = { 10 };
查看更多
爷的心禁止访问
4楼-- · 2019-09-29 07:45

Class members are defined inside the class, not outside:

class abc
{
    public:
    int x = 10;
};

Part of your problem is that you think b1.x is a class member. This is confusing classes and objects. abc is a class, and abc::x is a class member. b1.x is a member of an object. You can't define members of an object.

查看更多
对你真心纯属浪费
5楼-- · 2019-09-29 07:47

I don't fully understand your question, as it's too short and doesn't explain a lot, but I'll give it a go.

If you are trying to assign a value outside of function scope, that's simply not permitted by C++. C++ is not working like python/javascript where you assign values with the dot operator, and you are allowed to write them outside of scope.

If you are trying to set the class x variable as always 10 outside of scopes, you are looking for a static variable.

查看更多
6楼-- · 2019-09-29 07:52

Because, b1.x=10; is an assignment statement which cannot be present at file scope.

You can, however, use initialzation to provide the initial values. Something like

abc b1 = {10};
查看更多
登录 后发表回答