C++中的命名空间集1(引言) C++中的命名空间集合2(扩展名称空间和未命名命名空间)
null
- 正常方式
// 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
- “使用”指令
// 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