我觉得就 scope 来看变数的 visibility & lifespan
比区分哪个定义的 scope 有意义,
观念上能厘清即可
以下程式码有点杂乱
如果你可以了解 _number 是属于何种 scope
就 ok
复制程式
// -------------- test.h ---------------------
const int _number = 1000; // File scope
// -------------- test.c --------------------
// g++ compiles
#include <stdio.h>
#include "test.h"
extern const int _number; // File scope
class Foo { // beginning of class scope
public:
Foo(int _number) {
this->_number = _number;
}
int getnumber() {
return this->_number;
}
private:
int _number;
}; // end of class scope
int fun(int _number) { // start of function scope & local scope
return _number + 1;
} // end of function scope & local scope
int main(){
Foo * foo = new Foo(_number); // external _number in test.h
printf("foo->_number = %d at local level 1 \n", foo->getnumber()); // _number in class Foo
int _number = 0; // _number at local scope level 1
printf("_number = %d at level 1\n", _number);
while(true) { // start of local scope level 2
int _number = 3; // _number at local scope level 2
_number = fun(_number);
printf("_number = %d at level 2(while loop)\n", _number);
for( int _number = 100; _number < 103; _number++) {
printf("_number = %d at level 3(for loop)\n", _number); // local scope level 3
}
if (_number == 4) break;
} // end of local scope level 2
return 0;
}
输出如下:
foo->_number = 1000 at local level 1
_number = 0 at level 1
_number = 4 at level 2(while loop)
_number = 100 at level 3(for loop)
_number = 101 at level 3(for loop)
_number = 102 at level 3(for loop)
--
不完善的地方请大家指正