问题
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