名稱空間

名稱空間允許將類、物件和函式等實體按照名稱進行分組。 這樣,全域性範圍可以劃分為“子範圍”,每個子範圍都有自己的名稱。

名稱空間的格式為

namespace 識別符號
{
實體
}

其中識別符號是任何有效的識別符號,實體是包含在名稱空間內的類、物件和函式的集合。 例如

1
2
3
4
namespace myNamespace
{
  int a, b;
}

在這種情況下,變數a和 b是在名為myNamespace的名稱空間中宣告的普通變數。為了從myNamespace名稱空間外部訪問這些變數,我們必須使用作用域運算子::。例如,要從外部訪問之前的變數myNamespace我們可以寫

1
2
myNamespace::a
myNamespace::b

名稱空間的功能在全域性物件或函式可能使用與另一個物件或函式相同的識別符號時特別有用,這會導致重定義錯誤。 例如

// namespaces
#include <iostream>
using namespace std;

namespace first
{
  int var = 5;
}

namespace second
{
  double var = 3.1416;
}

int main () {
  cout << first::var << endl;
  cout << second::var << endl;
  return 0;
}
5
3.1416

在這種情況下,有兩個同名的全域性變數var。 一個定義在名稱空間first中,另一個定義在second中。由於名稱空間,不會發生重定義錯誤。

using

關鍵字using用於將名稱空間中的名稱引入到當前宣告區域。例如

// using
#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 first::x;
  using second::y;
  cout << x << endl;
  cout << y << endl;
  cout << first::y << endl;
  cout << second::x << endl;
  return 0;
}
5
2.7183
10
3.1416

請注意在此程式碼中,x(沒有任何名稱限定符)指的是first::xy指的是second::y,完全符合我們的using宣告。 我們仍然可以使用first::y的完整限定名。

using 關鍵字也可以用作指令來引入整個名稱空間

// using
#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;
  cout << x << endl;
  cout << y << endl;
  cout << second::x << endl;
  cout << second::y << endl;
  return 0;
}
5
10
3.1416
2.7183

在這種情況下,因為我們聲明瞭我們正在using namespace first,所以所有直接使用xy而沒有名稱限定符的都指的是namespace first.

using中的宣告僅在宣告它們的同一塊中有效,或者如果在全域性範圍內直接使用它們,則在整個程式碼中有效。 例如,如果我們打算首先使用一個名稱空間的物件,然後再使用另一個名稱空間的物件,我們可以這樣做

// using namespace example
#include <iostream>
using namespace std;

namespace first
{
  int x = 5;
}

namespace second
{
  double x = 3.1416;
}

int main () {
  {
    using namespace first;
    cout << x << endl;
  }
  {
    using namespace second;
    cout << x << endl;
  }
  return 0;
}
5
3.1416

命名空間別名


我們可以按照以下格式宣告現有名稱空間的備用名稱

namespace new_name = current_name;

名稱空間 std

C++ 標準庫中的所有檔案都在std名稱空間中聲明瞭其所有實體。 這就是為什麼我們通常在所有使用using namespace std;語句的程式中包含iostream.
Index
目錄