c++系列:匿名名稱空間

無.處安放的靈魂發表於2021-01-02

1.什麼是匿名名稱空間?

匿名名稱空間就是一個沒有名字的名稱空間。

namespace 
{
	func()
	{
		...
	}
}

2.匿名名稱空間有什麼用處?

  • 匿名名稱空間裡的內容只能被本檔案呼叫,不能被外部引用;
  • 匿名名稱空間中的變數特點跟全域性變數一樣,而函式特點像是新增了static的功能一樣。兩者僅此在本檔案使用

3.實驗

3.1在匿名空間中引用其它名稱空間

#include <iostream>

using namespace std;


namespace np
{
	void func1()
	{
		cout << "this is func1" << endl;
 	}
}

namespace
{
	void func2()
	{
		np::func1();
	}
}


int main()
{
	func2();
	return 0;
}

實驗結果
在這裡插入圖片描述

3.2匿名名稱空間中引用自己名稱空間中的方法

#include <iostream>

using namespace std;

namespace
{
	int cnt = 0;
	void func2()
	{
		cout << "this is func2" << endl;
	}
}

int main()
{
	cnt += 1;	//像全域性變數一樣讀取
	cout << cnt << endl;	
	func2();	//像全域性變數一樣讀取
	return 0;
}

實驗結果
在這裡插入圖片描述

3.3其他名稱空間中引用匿名名稱空間中的方法

#include <iostream>

using namespace std;

namespace
{
	void func2()
	{
		cout << "this is func2" << endl;
	}
}

namespace np
{
	void func1()
	{
		func2();
 	}
}

int main()
{
	np::func1();
	return 0;
}

實驗結果
在這裡插入圖片描述

3.4不同檔案呼叫匿名名稱空間

//test2.cpp
//namespace xxx {extern func1()};  //連名字元號都沒有,無法宣告....
void func1()
{
	func2();
}
test1.cpp
#include <iostream>

void func1();

using namespace std;

namespace
{
	void func2()
	{
		cout << "this is func2" << endl;
	}
}

int main()
{
	func1();
	return 0;
}

實驗結果
在這裡插入圖片描述
首先,匿名名稱空間沒有名字,或者說把名字給隱藏了,無法像xxx::func2()這樣子呼叫,並且在test2.cpp中也無法宣告匿名名稱空間空間(不符合語法)。

4.最後

匿名名稱空間的本質是什麼?
就是將名稱空間的名字元號給去掉,讓其他檔案找不到。
C++ 新的標準中提倡使用匿名名稱空間,而不推薦使用static,因為static用在不同的地方,涵義不同,容易造成混淆.另外,static不能修飾class。

相關文章