C++ variable scope

我们两清 提交于 2021-02-05 12:36:32

问题


I have C++ code different output compared to what I expected, I hope to understand how it's executed

#include <iostream>
#include <string>

int x = 8;

class A {
public:
    A() { 
        int x = 5 ;
    }

    void print (int x = 4) { 
         std::cout << "the scope variable"<< ::x << "passed variable" << x;
    }
};

int main() {
    A a;
    a.print(7);
}

I expected to be 5 and 7 but the result is 8 and 7


回答1:


If you expected the output 5 and 7 then the constructor has to deal with the global variable instead of the local variable.

That is instead of

A(){int x = 5 ;}

you should write either

A(){ x = 5 ;}

or

A(){ ::x = 5 ;}

Take into account that it would be better to declare the variable x as a static data member of the class A.

For example

class A {
    public :
    //...
    private:
        static int x;  
    };

//...

int A::x = 0;

In this case only objects of the class could access the variable.




回答2:


The constructor body of A is a no-op and is therefore a red herring. (You are declaring an int in local scope.)

The global variable x is always 8.

That is shadowed by the parameter name passed to print.

It would have been less uninteresting had the constructor body been x = 5;, then indeed the result would have been 5 and 7.



来源:https://stackoverflow.com/questions/44261802/c-variable-scope

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