C++中的命名空间集合2(扩展名称空间和未命名命名空间)

我们在下面的集合1中引入了名称空间。 C++中的命名空间集1(引言) 还可以在全局空间中创建多个名称空间。这可以通过两种方式实现。

null
  • 具有不同名称的名称空间

CPP

// A C++ program to show more than one namespaces
// with different names.
#include <iostream>
using namespace std;
// first name space
namespace first
{
int func() { return 5; }
}
// second name space
namespace second
{
int func() { return 10; }
}
int main()
{
// member function of namespace
// accessed using scope resolution operator
cout << first::func() <<"";
cout << second::func() <<"";
return 0;
}


  • 输出:
510
  • 扩展名称空间(使用相同的名称两次) 还可以创建两个同名的命名空间块。第二个名称空间块实际上是第一个名称空间的延续。简单地说,我们可以说这两个名称空间并没有不同,但实际上是相同的,它们是部分定义的。

CPP

// C++ program to demonstrate namespace extension
#include <iostream>
using namespace std;
// first name space
namespace first
{
int val1 = 500;
}
// rest part of the first namespace
namespace first
{
int val2 = 501;
}
int main()
{
cout << first::val1 <<"";
cout << first::val2 <<"";
return 0;
}


  • 输出:
500501

未命名名称空间

  • 它们可以直接在同一个程序中使用,并用于声明唯一标识符。
  • 在未命名名称空间中,名称空间声明中未提及的名称空间的名称。
  • 名称空间的名称由编译器唯一生成。
  • 您创建的未命名名称空间只能在创建它的文件中访问。
  • 未命名名称空间取代了静态变量声明。

CPP

// C++ program to demonstrate working of unnamed
// namespaces
#include <iostream>
using namespace std;
// unnamed namespace declaration
namespace
{
int rel = 300;
}
int main()
{
cout << rel << ""; // prints 300
return 0;
}


输出:

300

本文由 阿比纳夫·蒂瓦里 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享