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

前端 未结 4 453
野的像风
野的像风 2020-12-11 19:38

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

相关标签:
4条回答
  • 2020-12-11 20:16

    I think C++ doesn't support this.

    0 讨论(0)
  • 2020-12-11 20:18

    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.

    0 讨论(0)
  • 2020-12-11 20:35

    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.

    0 讨论(0)
  • 2020-12-11 20:41

    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 讨论(0)
提交回复
热议问题