C++ namespace相干語法實例剖析。本站提示廣大學習愛好者:(C++ namespace相干語法實例剖析)文章只能為提供參考,不一定能成為您想要的結果。以下是C++ namespace相干語法實例剖析正文
namespace定名空間是C++中一個異常主要的概念,本文實例展現了namespace的相干語法,供年夜家參考。詳細以下:
本段測試代碼包含以下內容:
(1) 若何拜訪namespace中聲明的稱號;
(2) namespace招致的相干抵觸;
(3) namespace可嵌套;
(4) 可以在namespace中應用using聲明和using編譯敕令;
(5) 未定名的namespace:其感化域為界說該namespace地點的聲明區域。C++推舉用來替換static界說靜態變量。
詳細法式代碼以下:
#include <iostream> using namespace std; namespace jerry{ int height; int weight; void showHeight(); string name; } // namespace jerry{ void showHeight() { cout<<"Method 3: Jerry height: "<<height<<" kg"<<endl; } } namespace elements { namespace fire { int flame; using namespace jerry; //(4) can use 'using' in namespace define using std::cout; } float water; } //(5) no name namespace //其感化域為界說時地點的聲明域,可用來調換static變量,這是C++尺度推舉的行動 namespace { string data; } void testFun(); int main() { cout<<"This code is to test namespace"<<endl; /*not allowed to define namespace in code segment //Error namespace jerry{ int height; int weight; } */ //(1) To access the data in namespace //Method 1: 感化域解析符 jerry::height = 165; cout<<"Method 1: Jerry height: " << jerry::height <<" cm"<<endl; //Method 2: using聲明 using jerry::weight; weight = 64; cout<<"Method 2: Jerry weight: " << weight<<" kg"<<endl; //Method 3: using編譯指令:All the define data in namespace jerry can be access. using namespace jerry; showHeight(); //(2) about name conflict { jerry::name = "Jerry"; string name = "Tom"; //using jerry::name; Error cout << "name: "<<name<<endl; /* This method will lead conflict with locall parameter using jerry::name; cout << "name: "<<name<<endl; */ cout << "name: "<<jerry::name<<endl; using namespace jerry; //部分變量會籠罩jerry定名空間的name界說 cout << "name: "<<name<<endl; } //(3) namespace can nest elements::fire::flame = 2; using namespace elements::fire; //(5) no name namespace //其感化域為界說時地點的聲明域,可用來調換static變量,這是C++尺度推舉的行動 data = "hello"; cout<<"No name namespace: data: " << data <<endl; testFun(); } void testFun() { /*not allowed to define namespace in code segment //Error namespace jerry{ int height; int weight; } */ //(5) no name namespace data = "hello in function"; cout<<"No name namespace: data: " << data <<endl; }
運轉成果以下圖所示: