len2 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #include <iostream>
  2. using namespace std;
  3. #if 0
  4. int a = 10; //全局变量
  5. void test01()
  6. {
  7. int a = 20;//局部变量
  8. cout << "局部变量a = " << a << endl; //优先选择局部变量
  9. //::作用域运算符(C++独有)
  10. cout << "全局变量a = " << ::a << endl; //取全局变量
  11. }
  12. //定义一个名字为A的命名空间(变量、函数)
  13. namespace A {
  14. int a = 100;
  15. }
  16. namespace B {
  17. int a = 200;
  18. }
  19. void test02()
  20. {
  21. //A::a a是属于A中的
  22. cout << "namespace A中的a = " << A::a << endl; //100
  23. cout << "namespace B中的a = " << B::a << endl; //200
  24. }
  25. namespace A {
  26. int a = 1000;
  27. namespace B {
  28. int a = 2000;
  29. }
  30. }
  31. void test03()
  32. {
  33. cout << "A中的a = " << A::a << endl;
  34. cout << "B中的a = " << A::B::a << endl;
  35. }
  36. //将c添加到已有的命名空间A中
  37. namespace A{
  38. int a = 100;
  39. int b = 200;
  40. }
  41. namespace A{
  42. int c = 300;
  43. }
  44. void test04()
  45. {
  46. cout << "A中的c = " << A::c << endl;
  47. }
  48. namespace A{
  49. int a = 100; //变量
  50. void func()
  51. {
  52. cout << "func遍历a = " <<a<<endl;
  53. }
  54. }
  55. void test05()
  56. {
  57. //变量的使用
  58. cout << "A中的a = " << A::a << endl;
  59. //函数的使用
  60. A::func();
  61. }
  62. namespace A{
  63. int a = 100;
  64. void func();
  65. }
  66. void A::func()
  67. {
  68. cout << "func遍历a = " << a << endl;
  69. }
  70. void funb()
  71. {
  72. cout << "funb遍历a = " << A::a << endl;
  73. }
  74. void test06()
  75. {
  76. A::func();
  77. funb();
  78. }
  79. #endif
  80. namespace veryLongName{
  81. int a = 10;
  82. void func()
  83. {
  84. cout << "hello namespace" << endl;
  85. }
  86. }
  87. void test()
  88. {
  89. namespace shortName = veryLongName;
  90. cout << "veryLongName::a : " << shortName::a << endl;
  91. veryLongName::func();
  92. shortName::func();
  93. }
  94. int main()
  95. {
  96. test();
  97. return 0;
  98. }