C ++变量范围 [英] C++ variable scope
本文介绍了C ++变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
与预期相比,我的C ++代码输出有所不同,我希望了解其执行方式
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);
}
我期望分别是5和7,但结果分别是8和7
I expected to be 5 and 7 but the result is 8 and 7
推荐答案
如果期望输出5和7,则构造函数必须处理全局变量而不是局部变量.
If you expected the output 5 and 7 then the constructor has to deal with the global variable instead of the local variable.
那不是
A(){int x = 5 ;}
您应该写
A(){ x = 5 ;}
或
A(){ ::x = 5 ;}
请注意,最好将变量 x
声明为类 A
的静态数据成员.
Take into account that it would be better to declare the variable x
as a static data member of the class A
.
例如
class A {
public :
//...
private:
static int x;
};
//...
int A::x = 0;
在这种情况下,只有类的对象才能访问该变量.
In this case only objects of the class could access the variable.
这篇关于C ++变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文