c++ namespace命名空间详解
What is a namespace?
A namespace defines an area of code in which all identifiers are guaranteed to be unique. By default, all variables and functions are defined in the global namespace. For example, take a look at the following snippet:
|
1
2
3
4
5
|
int nX = 5;int foo(int nX){ return -nX;} |
Both nX and foo() are defined in the global namespace.
Namespaces allow to group entities like classes, objects and functions under a name. This way the global scope can be divided in "sub-scopes", each one with its own name.
命名空间把对象,函数,变量等分组,然后有一个名字。
The format of namespaces is:
namespace identifier
{
entities
}
Where identifier is any valid identifier and entities is the set of classes, objects and functions that are included within the namespace. For example:
实体可以是任何有效的标识符。
namespace myNamespace
{
int a, b;
}
In this case, the variables a and b are normal variables declared within a namespace called myNamespace. In order to access these variables from outside the myNamespace namespace we have to use the scope operator ::. For example, to access the previous variables from outside myNamespace we can write:
|
|
The functionality of namespaces is especially useful in the case that there is a possibility that a global object or function uses the same identifier as another one, causing redefinition errors. For example:
// namespaces
#include <iostream>
using namespace std; namespace first
{
int var = ;
} namespace second
{
double var = 3.1416;
} int main () {
cout << first::var << endl;
cout << second::var << endl;
return ;
}
n this case, there are two global variables with the same name: var. One is defined within the namespace firstand the other one in second. No redefinition errors happen thanks to namespaces.
using
The keyword using is used to introduce a name from a namespace into the current declarative region. For example:
#include <iostream>
using namespace std; namespace first
{
int x = ;
int y = ;
} namespace second
{
double x = 3.1416;
double y = 2.7183;
} int main () {
using first::x;
using second::y;
cout << x << endl;
cout << y << endl;
cout << first::y << endl;
cout << second::x << endl;
return ;
}
5
2.7183
10
3.1416Notice how in this code, x (without any name qualifier) refers to first::x whereas y refers to second::y, exactly as our using declarations have specified. We still have access to first::y and second::x using their fully qualified names. The keyword using can also be used as a directive to introduce an entire namespace:using可以引入整个namespace。
// using
#include <iostream>
using namespace std; namespace first
{
int x = ;
int y = ;
} namespace second
{
double x = 3.1416;
double y = 2.7183;
} int main () {
using namespace first;
cout << x << endl;
cout << y << endl;
cout << second::x << endl;
cout << second::y << endl;
return ;
}
In this case, since we have declared that we were using namespace first, all direct uses of x and y without name qualifiers were referring to their declarations in namespace first.
using and using namespace have validity only in the same block in which they are stated or in the entire code if they are used directly in the global scope. For example, if we had the intention to first use the objects of one namespace and then those of another one,
using 和using namespace 仅仅在他们声明的代码块有效,如果在全局作用域中直接使用,则在整个代码块中有效。
we could do something like:
// using namespace example
#include <iostream>
using namespace std; namespace first
{
int x = ;
} namespace second
{
double x = 3.1416;
} int main () {
{
using namespace first;
cout << x << endl;
}
{2
using namespace second;
cout << x << endl;
}
return ;
}
5
3.1416
Namespace alias
We can declare alternate names for existing namespaces according to the following format: namespace new_name = current_name;命名空间里的变量冲突:
#include<iostream>
using namespace std;
int x=;
int y=;
namespace first
{
int var=;
int x=;
int y=;
}
namespace second
{
double var=3.1416;
double x=5.5;
double y=10.5;
}
int main()
{
using namespace first;
cout<<x<<endl;
x显示冲突
}
命名空间嵌套:
C++ does not allow compound names for namespaces.
// pluslang_namespace.cpp
// compile with: /c
// OK
namespace a {
namespace b {
int i;
}
} // not allowed
namespace c::d { // C2653
int i;
}
下面的代码嵌套命名空间;
#include<iostream>
using namespace std; namespace A
{
void fun1(){ cout<<"fun1"<<endl; } namespace B
{
int a=;
void fun1(){ cout<<"b fun1"<<endl;}
}
}
int main()
{
using namespace A;
fun1(); //print fun1
B::fun1(); //print b fun1
}
我们也可以用;
A::fun1();
A::B::fun1();
结果一样。(某个名字在自己的空间之外使用,在反复地在前面加上名字空间作为限定词)
无名名字空间,无名名字空间主要是保持代码的局部性,使用如下:
namespace
{
const int CVAR1 = 1;
void test();
}
由于该命名空间没有名字,不能被外部范围。(有什么用,我们可以
但一定要注意的一点是,在C++编译器实现时,无名名字空间其实是有名字的,这个隐含的名字跟它所在编译单元名字相关。所以基于这一点,我们不能跨编译单元使用无名名字空间中的名字。
上面的声明等价于
namespace $$$
{
const int CVAR1 = ;
void test();
}
using namespace $$$;
其中$$$在其所在的作用域里具有惟一性的名字,每个编译单元里的无名名字空间也是互不相同的,using namesapce $$$只是当前的编译单元的隐含名字,所以不能跨编译单元使用无名名字空间中的名字。
假设上面的test方法在是a.h与a.cpp中定义与实现的,但在b.h或b.cpp中就不能直接使用test方法或CVAR1。因为在b的这个编译单元中链接的是b这个编译单元中的test符号,并非a编译单元中的test符号,也就会出现未定符号。
要避免名字空间使用很短的名字,也不能太长,更不能嵌套太深了,个人觉得不要超过4层。
命名空间可以是不连续的
一个命名空间可以分散定义在多个文件中。不过,如果命名空间的一个部分需要使用一个定义在另一文件中的名字,必须声明该名字。
namespace namespace_name {
// declarations
}
如果namespace_name不是引用前面定义的命名空间,则用该名字创建新的命名空间,否则,这个定义打开一个已存在的命名空间,并将新声明加到那个命名空间。
接口和实现的分离
可以用分离的接口文件和实现文件构成命名空间。可以用与管理类和函数定义相同的方法来组织命名空间。定义多个不相关类型的命名空间应该使用分离的文件分别定义每个类型。
// sales_item.h
namespace cplusplus_primer {
class SalesItem { /* … */ };
SalesItem operator+(const SalesItem&, const SalesItem&);
} // query.h
namespace cplusplus_primer {
class Query {
public:
Query(const std::string&);
std::ostream & display(std::ostream&) const;
};
} // sales_item.cpp
#include “sales_item.h”
namespace cplusplus_primer {
// definitions for SalesItem members and overloaded operators
} // query.cpp
#include “query.h”
namespace cplusplus_primer {
// definitions for Query members and related functions
}
示例:
namespace C //命名空间不连续1.h
{
class A
{
private:
int a,b;
public:
void func();
};
}
#include"命名空间不连续1.h"
#include<iostream>
using namespace std;
namespace C
{
void A::func()
{
a=,b=;
cout<<a<<b<<endl;
cout<<"fun1"<<endl;
}
} int main()
{
using namespace C;
A a;
a.func();
}
定义命名空间成员
可以在命名空间定义的外部定义命名空间成员,类似于在类外部定义类成员的方式。
// namespace members defined outside the namespace must use qualified names
cplusplus_primer::operator+(const SalesItem&, const SalesItem&)
{
SalesItem ret(lhs);
// …
}
c++ namespace命名空间详解的更多相关文章
- linux命名空间详解_转
转自: Linux的命名空间详解--Linux进程的管理与调度(二) Linux Namespaces机制提供一种资源隔离方案. PID,IPC,Network等系统资源不再是全局性的,而是属于特定的 ...
- C++命名空间详解
使用命名空间的目的是对标识符的名称进行本地化,以避免命名冲突.在C++中,变量.函数和类都是大量存在的.如果没有命名空间,这些变量.函数.类的名称将都存在于全局命名空间中,会导致很多冲突.比如,如果我 ...
- C#命名空间详解namespace
命名空间是一个域,这在个域中所有的类型名字必须是唯一的,不同的类型分组归入到层次化的命名空间, 命名空间的好处是:1.避免名字冲突,2.便于查找类型名字. 如:System.secruity.Cry ...
- [转载]C++之using namespace std 详解与命名空间的使用
来源:https://blog.csdn.net/Bruce_0712/article/details/72824668 所谓namespace,是指标识符的各种可见范围.C++标准程序库中的所有标识 ...
- django 命名空间详解
include(module[, namespace=None, app_name=None ]) include(pattern_list) include((pattern_list, app_n ...
- Linux的命名空间详解--Linux进程的管理与调度(二)【转】
Linux Namespaces机制提供一种资源隔离方案. PID,IPC,Network等系统资源不再是全局性的,而是属于特定的Namespace.每个Namespace里面的资源对其他Namesp ...
- Linux的命名空间详解--Linux进程的管理与调度(二)
转自:http://blog.csdn.net/gatieme/article/details/51383322 日期 内核版本 架构 作者 GitHub CSDN 2016-05-12 Linux- ...
- c++的重载 缺省参数和命名空间详解
参加了几次笔试,发现有很多c++方面的问题被卡了.从现在开始进攻c++.之后会陆续更新c++学习笔记. 先说说我学习的书籍,大家如果有好的书籍推荐,感谢留言. 暂时是在看这些书自学. 1.C++介绍. ...
- Thinkphp5.0实战开发一------命名空间详解
序言 ThinkPHP是一个快速.兼容而且简单的轻量级国产PHP开发框架,使用ThinkPHP框架可以极大简化我们的开发过程,节省时间.这个专题我将记录自己学习使用ThinkPHP5.0的进行实战开发 ...
随机推荐
- (C#)Windows Shell 编程系列4 - 上下文菜单(iContextMenu)(二)嵌入菜单和执行命令
原文(C#)Windows Shell 编程系列4 - 上下文菜单(iContextMenu)(二)嵌入菜单和执行命令 (本系列文章由柠檬的(lc_mtt)原创,转载请注明出处,谢谢-) 接上一节:( ...
- dojo 学习笔记
1 因为Dijit包括了一系列的UI组件,他绑定了4个支持的主题:nihilo, soria, tundra 和claro.每个主题包括了一系列的图片和CSS文件来控制组件的外观.CSS文件必须显示 ...
- express文件上传
安装express,创建项目,添加sqlite3模块 express --sessions --css stylus --ejs myhotel npm install sqlite3node app ...
- 令人作呕的OpenSSL
在OpenSSL心脏出血之后,我相信非常多人都出了血,而且流了泪...网上瞬间出现了大量吐嘈OpenSSL的文章或段子,仿佛内心的窝火一瞬间被释放了出来,跟着这场疯闹,我也吐一下嘈,以雪这些年被Ope ...
- jQuery也能舞出绚丽的界面(完结篇)
ThematicMap又增加了两种Chart类型,现在总算是齐全了,效果也出来了,与大家分享一下: 1.MultiSelect选择界面: 颜色框是可以选择颜色的: 2.生成的饼图效果: 3.生成的柱状 ...
- nvarchar and nchar
Same: 1.store unicode charactor. 2. A charactor is stroed with 2 bytes. Different. 1. nchar 会自动填充数据 ...
- JavaSE学习总结第01天_Java概述
01.01 计算机概述 计算机(Computer):全称电子计算机,俗称电脑. 是一种能够按照程序运行,自动.高速处理海量数据的现代化智能电子设备. 由硬件和软件所组成,没有安装任何软件的计算机称 ...
- BZOJ 1617: [Usaco2008 Mar]River Crossing渡河问题( dp )
dp[ i ] = max( dp[ j ] + sum( M_1 ~ M_( i - j ) ) + M , sum( M_1 ~ M_i ) ) ( 1 <= j < i ) 表示运 ...
- SpringMVC请求访问不到静态文件解决方式
如何你的DispatcherServlet拦截"*.do"这样的有后缀的URL,就不存在访问不到静态资源的问题. 如果你的DispatcherServlet拦截"/&qu ...
- ThinkPHP第五天(提交类型判定常量IS_POST等,错误页面种类,Model实例化方式,模板中使用函数,foreach循环,模板中.语法配置)
1.IS_GET.IS_POST.IS_PUT.IS_DELETE.IS_AJAX常量,方便快捷实现各个判断. 在Action类中还可以使用$this->isPost()等进行判断. 2.错误页 ...