簡體   English   中英

Scope 具有塊陰影的分辨率運算符

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM