can we make global variables by defining a class variable outside of the class with “dot” operator?

你。 提交于 2019-12-25 20:28:32

问题


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?


回答1:


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



回答2:


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



回答3:


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.




回答4:


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).




回答5:


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.



来源:https://stackoverflow.com/questions/41510453/can-we-make-global-variables-by-defining-a-class-variable-outside-of-the-class-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!