服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - 深入解析C++编程中范围解析运算符的作用及使用

深入解析C++编程中范围解析运算符的作用及使用

2021-03-19 13:50C++程序设计 C/C++

这篇文章主要介绍了C++编程中范围解析运算符的使用方法,是C++入门学习中的基础知识,需要的朋友可以参考下

范围解析运算符 :: 用于标识和消除在不同范围内使用的标识符。
语法

 

复制代码 代码如下:

:: identifier class-name :: identifier namespace :: identifier enum class :: identifier enum struct :: identifier

 

 


备注
identifier 可以是变量、函数或枚举值。
具有命名空间和类
以下示例显示范围解析运算符如何与命名空间和类一起使用:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace NamespaceA{
  int x;
  class ClassA {
  public:
    int x;
  };
}
 
int main() {
 
  // A namespace name used to disambiguate
  NamespaceA::x = 1;
 
  // A class name used to disambiguate
  NamespaceA::ClassA a1;
  a1.x = 2;
 
}

没有范围限定符的范围解析运算符表示全局命名空间。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
namespace NamespaceA{
  int x;
}
 
int x;
 
int main() {
  int x;
 
  // the x in main()
  x = 0;
  // The x in the global namespace
  ::x = 1;
 
  // The x in the A namespace
  NamespaceA::x = 2;
}

你可以使用范围解析运算符来标识命名空间的成员,还可标识通过 using 指定成员的命名空间的命名空间。在下面的示例中,你可以使用 NamespaceC 限定 ClassB(尽管 ClassB 已在 NamespaceB 中声明),因为已通过 using 指令在 NamespaceC 中指定 NamespaceB。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace NamespaceB {
  class ClassB {
  public:
    int x;
  };
}
 
namespace NamespaceC{
  using namespace B;
 
}
int main() {
  NamespaceB::ClassB c_b;
  NamespaceC::ClassB c_c;
 
  c_b.x = 3;
  c_c.x = 4;
}

可使用范围解析运算符链。在以下示例中,NamespaceD::NamespaceD1 将标识嵌套的命名空间 NamespaceD1,并且 NamespaceE::ClassE::ClassE1 将标识嵌套的类 ClassE1。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace NamespaceD{
  namespace NamespaceD1{
    int x;
  }
}
 
namespace NamespaceE{
 
  class ClassE{
  public:
    class ClassE1{
    public:
      int x;
    };
  };
}
 
int main() {
  NamespaceD:: NamespaceD1::x = 6;
  NamespaceE::ClassE::ClassE1 e1;
  e1.x = 7 ;
}

具有静态成员
必须使用范围解析运算符来调用类的静态成员。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
class ClassG {
public:
  static int get_x() { return x;}
  static int x;
};
 
int ClassG::x = 6;
 
int main() {
 
  int gx1 = ClassG::x;
  int gx2 = ClassG::get_x();
}

具有区分范围的枚举
区分范围的解析运算符还可以与区分范围的枚举枚举声明的值一起使用,如下例所示:

?
1
2
3
4
5
6
7
8
9
10
enum class EnumA{
  First,
  Second,
  Third
};
 
int main() {
 
  EnumA enum_value = EnumA::First;
}

延伸 · 阅读

精彩推荐