C++:命名空间
1,命名空間簡(jiǎn)介
命名空間隨標(biāo)準(zhǔn)C++而引入,相當(dāng)于一個(gè)靈活的文件域(全局域),以關(guān)鍵字namespace開頭給其起個(gè)名字,并用大括號(hào)把定義區(qū)域括起來(聲明塊)。
在域外使用域內(nèi)成員時(shí),需要加上命名空間名作為前綴,再加上域操作符“::”,可以使用嵌套定義。
如果在關(guān)鍵字namespace之前使用using,就不必使用限定修飾名,即可以一次性使命名空間中所有成員都可以直接被使用。
標(biāo)準(zhǔn)C++庫(kù)中所有組件都在std的命名空間中聲明和定義的,在標(biāo)準(zhǔn)C++平臺(tái)調(diào)用如下語句:
using namespace std;
便可直接使用標(biāo)準(zhǔn)C++庫(kù)中所有成員,注意:如果使用命名空間std,則#include編譯預(yù)處理命令包含頭文件時(shí),必須去掉擴(kuò)展名(.h)。
2,常見問題分析
2.1 使用標(biāo)準(zhǔn)C++命名空間std時(shí),加載頭文件:
錯(cuò)誤代碼:
#include<iostream.h>
using namespace std;
void main()
{cout<<"Hello,world!"<<endl;getchar();
}
錯(cuò)誤 1 error C1083: 無法打開包括文件:“iostream.h”: No such file or directory c:\users\dell\documents\visual studio 2012\projects\project\project\code1.cpp 1 1 Project
分析:
在標(biāo)準(zhǔn)C++命名空間std,<iostream.h>和不同,C++標(biāo)準(zhǔn)明確提出不支持后綴為(.h)的頭文件(為了與C區(qū)別和正確使用命名空間)。
正確代碼:
#include<iostream.h>
using namespace std;
void main()
{cout<<"Hello,world!"<<endl;getchar();
}
2.2 命名沖突:
錯(cuò)誤代碼:
#include"class1.h"
#include"class2.h"
#include<iostream>
using namespace std;
void main()
{MyClass x;MyClass y;x.Info();y.Info();getchar();
}//class1.h
#include<iostream>
using namespace std;
class MyClass
{
public:void Info(){cout<<"頭文件class1.h"<<endl;}
};//class2.h
#include<iostream>
using namespace std;
class MyClass
{
public:void Info(){cout<<"頭文件class2.h"<<endl;}
};
錯(cuò)誤 1 error C2011: “MyClass”:“class”類型重定義 c:\users\dell\documents\visual studio 2012\projects\project\project\class2.h 4 1 Project
分析:
class1.h和class2.h頭文件都定義了類MyClass,導(dǎo)致名字沖突,編譯器認(rèn)為MyClass被重復(fù)定義。解決辦法之一改動(dòng)其中一個(gè)類名,之二在class1.h和class2.h頭文件中都引入namespace。
正確代碼:
#include"class1.h"
#include"class2.h"
#include<iostream>
using namespace std;
void main()
{MyNamespace1::MyClass x;MyNamespace2::MyClass y;x.Info();y.Info();getchar();
}//class1.h
#include<iostream>
using namespace std;
namespace MyNamespace1
{
class MyClass
{
public:void Info(){cout<<"頭文件class1.h"<<endl;}
};
};//class2.h
#include<iostream>
using namespace std;
namespace MyNamespace2
{
class MyClass
{
public:void Info(){cout<<"頭文件class2.h"<<endl;}
};
};
總結(jié)
- 上一篇: 走进人工智能,认识机器学习
- 下一篇: 求一个帅气的个性签名。