C++_命名空间namespace 与 using编译指令 与 using声明使用。

来源:互联网 发布:淘宝怎么改登入密码 编辑:程序博客网 时间:2024/06/06 18:44

命名空间:

C++中允许用户创建自己的用户空间。可以通过关键字namespace 声明即可

需要注意的事项:

名称空间可以是全局的,也可以位于另一个名称空间中,但不能位于代码块中。

示例代码如下:

#include <iostream>using namespace std;namespace Jill{double bucket(double a){ return a + 3; }double fetch;struct Hill{int a;int b;};};int main(){Jill::fetch = 3;cout << Jill::bucket(2) << endl;return 0;}



using指令:


using 声明使特定的标示符可用。

示例如下:如同使用了包里的一个变量,在接下来的作用域里不需要显示使用作用域标示符,也不能定义同名变量。

#include <iostream>using namespace std;namespace Jill{double bucket(double a){ return a + 3; }double fetch;struct Hill{int a;int b;};};int main(){using Jill::fetch;Jill::fetch = 7;double fetch;cin >> fetch;cout << fetch << endl;cout << Jill::fetch << endl;cout << Jill::bucket(2) << endl;return 0;}







using 编译指令使整个名称空间可用。

#include <iostream>using namespace std;namespace Jill{double bucket(double a){ return a + 3; }double fetch;struct Hill{int a;int b;};};int main(){using namespace Jill;Jill::fetch = 7;//double fetch;cin >> fetch;cout << fetch << endl;cout << Jill::fetch << endl;cout << Jill::bucket(2) << endl;return 0;}


命名空间是开放的(open),可以把名称加入到已有的名称空间中。例如下面的语句:

namespace Jill{

char * goose(const char *);

}

可以在文件的后面(或另外一个文件中)再次使用Jack名称空间来提供该函数的代码。

namespace Jill{

char * goose(const char * xx){

.........

}

}


可以给命名空间取别名。

如:namespace mvft  =  my_very_favorite_things;

namespace MEF =  myth::elements::fire;


#include <iostream>using namespace std;namespace Jill{double bucket(double a){ return a + 3; }double fetch;struct Hill{int a;int b;};namespace Pick{int abile;}};namespace tank = Jill::Pick;int main(){Jill::fetch = 3;tank::abile = 4;cout << tank::abile << endl;cout << Jill::bucket(2) << endl;return 0;}



可以定义省略名称空间的名称来创建未命名的名称空间:

namespace{

int  ice;

int  bandycoot;

}

                                             
0 0
原创粉丝点击