[英]Scope resolution operator with shadowing in blocks
並不是說您會編寫這樣的代碼,而是試圖更好地理解 scope 分辨率運算符::
。 是否可以訪問將值2
存儲在內部 scope 中的foo
版本,而無需將其命名為命名空間?
#include <iostream>
using std::endl;
using std::cout;
// Some global.
int foo = 1;
int main() {
cout << foo << endl; //<-- Prints 1.
// Shadow it:
int foo = 2;
cout << foo << endl; //<-- Prints 2.
// Access the global:
cout << ::foo << endl; //<-- Prints 1.
{
// More shadows:
int foo = 3;
cout << foo << endl; // The local. 3.
cout << ::foo << endl; // The global, 1
//cout << ::main::foo << endl; //<-- Obviously invalid.
// ::..::foo // Totally not it.
// Is it possible go access 2 here?
}
}
謝謝!
go 可以在這里訪問 2 嗎?
不,無法訪問第二個foo
,因為它已從內部foo
隱藏。
如果您必須使用#2
中的外部foo
,您可以做的一件事是,您可以使用其他名稱(如ref
)為其創建別名,然后使用該別名,如下所示:
// Some global.
int foo = 1;
int main() {
cout << foo << endl;
// Shadow it:
int foo = 2;
cout << foo << endl;
cout << ::foo << endl;
{
//------------v-------------->create alias lvalue reference
int const& ref = foo;
int foo = 3;
cout << foo << endl;
cout << ::foo << endl;
// possible to access foo from #2 using alias ref but not using the name foo
std::cout<<ref; //prints 2
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.