標籤:cpp nbsp class 訪問 log 使用 存在 div data
1命名空間解決全域變數的衝突
1 main.h檔案 2 #pragma once 3 // data命名空間的名稱 4 namespace data 5 { 6 int num = 20;//外部全域變數衝突 7 } 8 9 10 main.cpp11 #include"main.h"12 #include<iostream>13 using namespace std;14 15 int num = 10;16 17 void main()18 {19 cout << num << endl;20 cout << data::num << endl;//::域作用符 此處必須使用域作用符21 22 cin.get();23 }
2命名空間沒有私人,全部變數,函數都是公有,可以訪問
using namespace data;//使用命名空間,直接存取當作全域變數
內層覆蓋外層,
::num 直接存取全域變數,全域變數不存在就是0
使用命名空間必須在定義之後
#include<iostream>using namespace std;//命名空間沒有私人,全部變數,函數都是公有,可以訪問//using namespace data;//使用命名空間,直接存取當作全域變數//內層覆蓋外層,//::num 直接存取全域變數,全域變數不存在就是0//使用命名空間必須在定義之後namespace data{ int num; void show() { cout << num << endl; }}using namespace data;//使用命名空間,直接存取當作全域變數//內層覆蓋外層,namespace dataX{ int num=100; namespace run { int num = 10; void show() { //::num 直接存取全域變數,全域變數不存在就是0 cout << dataX::num << endl; } }}using namespace dataX;//使用命名空間必須在定義之後void main(){ dataX::run::show(); cin.get();}void main1x(){ data::num = 10; show(); cin.get();}
3命名空間的使用
1 #include<iostream> 2 #include<cstdlib> 3 using namespace std; 4 5 6 namespace string1 7 { 8 char str[10]{ "calc" }; 9 }10 namespace string211 {12 char str[10]{ "notepad" };13 }14 //命名空間拓展,名稱相同,同一個命名空間15 //瀑布式開發16 namespace string217 {18 char cmd[10]{ "notepad" };19 void show()20 {21 cout << str << endl;22 }23 }24 25 //命名空間,可以無限嵌套26 namespace run27 {28 namespace runit29 {30 namespace runitout31 {32 int num = 100;33 void show()34 {35 cout << num << endl;36 }37 }38 }39 40 }41 42 43 void main()44 {45 //system(string2::str);46 //string2::show();//命名空間的函數與變數47 run::runit::runitout::num = 199;48 run::runit::runitout::show();49 50 51 52 system("pause");53 }
4匿名命名空間
1 #include<iostream> 2 3 using namespace std; 4 5 6 //匿名命名空間等同全域變數 7 namespace 8 { 9 int x = 10;10 }11 12 13 void main()14 {15 x = 3;16 cout << x << endl;17 18 19 cin.get();20 21 }
c++之命名空間namespace