开发者

Is there a way to access the value of a local variable that has become hidden inside another scope?

I know if a variable is global, the you can always access its value by preceding the variable name w开发者_如何学Pythonith ::... but is there a way to access the value of a local variable that has become hidden inside another scope?

I thinking of something like this:

void f() {
    int x = 1;
    {
        int x = 2;
        //access the value of the variable x (with the 1 in it) inside here
    }
}

If the language doesn't support this, then I'm perfectly okay with some hacky solution.


You could assign the outer x's address to a pointer object, then refer to it via the pointer in the inner scope (assuming you don't have another pointer object of the same name hiding it).

Or, as long as you're editing the code, you could change the name.


I think C++ doesn't support this.


I don't think so. Unless the shadowed variable is a global variable, a variable in another namespace or a member variable of the class or of any of its ancestors or of any other class, it remains inaccessible.

There might be some compiler-specific trickery with the using keyword, but I wouldn't trust it.

By the way, using is very useful if you accidentally "shadow" a method in a subclass with a method of the same name but different signature.


C++ does not allow this.

How hacky do you want to get? Because you know the first variable will be next to the second on the stack. Check with a debugger. Not very portable but you could try it if you need.

(&x+1)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜