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

本秂侑毒 提交于 2019-12-17 20:50:20

问题


I know if a variable is global, the you can always access its value by preceding the variable name with ::... 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.


回答1:


I think C++ doesn't support this.




回答2:


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.




回答3:


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.




回答4:


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)


来源:https://stackoverflow.com/questions/7047621/is-there-a-way-to-access-the-value-of-a-local-variable-that-has-become-hidden-in

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