12

次のコードを記述すると、適切にコンパイルおよび実行されます。

#include <iostream>
using namespace std;

namespace first
{
  int x = 5;
  int y = 10;
}

namespace second
{
  double x = 3.1416;
  double y = 2.7183;
}

int main () {
  using namespace first; //using derective
  using second::y;
  cout << x << endl;
  cout << y << endl;
  return 0;
}

しかし、次のように main 関数の外でディレクティブを使用して記述すると、

using namespace first; //using derective
using second::y;
int main () {
  cout << x << endl;
  cout << y << endl;
  return 0;
}

次のコンパイル エラーが発生します。

g++     namespace03.cpp   -o namespace03
namespace03.cpp: In function ‘int main()’:
namespace03.cpp:20:11: error: reference to ‘y’ is ambiguous
namespace03.cpp:13:10: error: candidates are: double second::y
namespace03.cpp:7:7: error:                 int first::y
make: *** [namespace03] Error 1

mainusing ディレクティブが insideと outsideで使用されると動作が異なる理由を誰か説明できますmainか?

4

2 に答える 2

11

using-declaration はまさにその宣言です。mainのusing second::y;内部は、そのスコープで変数を宣言することに似ており、グローバル名前空間スコープ内のy他の s を隠します。yグローバル スコープで使用する場合using second::y;、両方yの が同じスコープにあるため、名前を非表示にすることはありません。

最初の例が次のようなものだと想像してください (説明については、以下のコメントを参照してください)。

namespace first
{
  int x = 5;
  int y = 10;
}

int main () {
  using namespace first; // This makes first::y visible hereafter
  int y = 20; // This hides first::y (similar to using second::y)
  cout << x << endl;
  cout << y << endl; // Prints 20 
}

ただし、2 番目の例は次のようになります。

namespace first
{
  int x = 5;
  int y = 10;
}
using namespace first; // This makes first::y visible in global scope
int y = 20; // This is global ::y
int main () {
  cout << x << endl;
  cout << y << endl; // Error! Do you mean ::y or first::y?
}
于 2013-06-25T21:00:38.353 に答える