C++中的命名空间集合3(访问、创建头、嵌套和混叠)

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

null

访问命名空间的不同方式

  1. 正常方式

    // C++ program to demonstrate accessing of variables
    // in normal way, i.e., using "::"
    #include <iostream>
    using namespace std;
    namespace geek
    {
    int rel = 300;
    }
    int main()
    {
    // variable ‘rel’ accessed
    // using scope resolution operator
    cout << geek::rel << "" ; // prints 300
    return 0;
    }

    
    

    输出:

    300
    
  2. “使用”指令

    // C++ program to demonstrate accessing of variables
    // in normal way, i.e., using "using" directive
    #include <iostream>
    using namespace std;
    namespace geek
    {
    int rel = 300;
    }
    // use of ‘using’ directive
    using namespace geek;
    int main()
    {
    // variable ‘rel’ accessed
    // without using scope resolution variable
    cout << rel << "" ; //prints 300
    return 0;
    }

    
    

    输出:

    300
    

在头文件中使用名称空间

  • 我们需要创建两个文件。一个包含名称空间和我们以后要使用的所有数据成员和成员函数。
  • 另一个程序可以直接调用第一个程序来使用其中的所有数据成员和成员函数。

文件1

// file1.h
namespace foo
{
int value()
{
return 5;
}
}


文件2

// file2.cpp - Not to be executed online
#include <iostream>
#include “file1.h” // Including file1
using namespace std;
int main ()
{
cout << foo::value();
return 0;
}


在这里,我们可以看到名称空间是在file1中创建的。h,该名称空间的value()在file2中被调用。cpp。

嵌套名称空间

// C++ program to demonstrate nesting of namespaces
#include <iostream>
using namespace std;
// Nested namespace
namespace out
{
int val = 5;
namespace in
{
int val2 = val;
}
}
// Driver code
int main()
{
cout << out::in::val2; // prints 5
return 0;
}


输出:

5

命名空间别名

namespace new_name = current_name;

#include <iostream>
namespace name1
{
namespace name2
{
namespace name3
{
int var = 42;
}
}
}
// Aliasing
namespace alias = name1::name2::name3;
int main()
{
std::cout << alias::var << '' ;
}


输出:

42

本文由 阿比纳夫·蒂瓦里 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

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