0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C++ 名前空間とは

Last updated at Posted at 2021-07-02

名前空間とは

名前空間は識別子の住所。名前の衝突を避けるために使われます。

namespace name {
...
}

以下のように、スコープ解決演算子を用いて指定します。

name::member;

スコープ解決演算子を使用した書き方

# include <iostream>

namespace hello {
	void print() {
		std::cout << "hello world\n" << std::endl;
	}
}

int main() {
	hello::print();
}

usingディレクティブ

以下で、呼び出したスコープにおいて名前空間にあるすべてのものをスコープに挿入できます。

using namespace name;

usingディレクティブを使用した書き方

# include <iostream>

namespace hello {
	using namespace std;
	void print() {
		cout << "hello world\n" << endl;
	}
}

int main() {
	hello::print();
}

usingディレクティブをスコープの外で使用した書き方

以下でも動きます。スコープの外でusingされているstdをhelloは使用することができます。

# include <iostream>

using namespace std;

namespace hello {
	void print() {
		cout << "hello world\n" << endl;
	}
}

int main() {
	hello::print();
}

using宣言を使用した書き方

using宣言を使用することで、特定のメンバを取り込むことができます。

# include <iostream>

namespace hello {
	using std::cout;
	using std::endl;
	void print() {
		cout << "hello world\n" << endl;
	}
}

int main() {
	hello::print();
}

参考

c++ using使い方の名称まとめ - Qiita
名前空間 (C++) | Microsoft Docs
C++ 関数やクラスを個別にusingする方法【using宣言、エイリアス宣言】 | MaryCore
名前空間

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?