C++程式碼中開頭常看到using namespace的敘述,其用途如下。
using及namespace皆為C++的關鍵字。
namespace
namespace作用為定義一個命名空間,不同命名空間內的關鍵字可以重複。例如下面以namespace定義命名空間foo及bar及所屬的變數名稱x有不同的值,兩命名空間都可使用同樣的變數名稱x,使用時在程式中在名稱前加上命名空間的修飾來引入。
main.cpp
#include <iostream>
using namespace std;
namespace foo {
int x = 1;
}
namespace bar {
int x = 10;
}
int main() {
cout << foo::x << endl; // 1
cout << bar::x << endl; // 10
return 0;
}
using
using為將一個命名空間的名稱引入所在的程式區域中,如此即可省略命名空間的修飾。
例如下面使用using foo::y則把命名空間foo的變數名稱y引入所在區塊,則該區塊引用該命名空間的實體名稱時即可省略命名空間的修飾。
main.cpp
#include <iostream>
using namespace std;
namespace foo {
int x = 1;
int y = 2;
}
int main() {
cout << foo::x << endl; // 1
using foo::y;
cout << y << endl; // 2
return 0;
}
using namesapce
using namespace則為引入整個命名空間的名稱至所在區域,則引用該命名空間的名稱時皆可省略命名空間的修飾。
main.cpp
#include <iostream>
using namespace std;
namespace foo {
int x = 1;
int y = 2;
}
int main() {
using namespace foo;
cout << x << endl; // 1
cout << y << endl; // 2
return 0;
}
沒有留言:
張貼留言