手机
当前位置:查字典教程网 >编程开发 >C语言 >深入解析C++编程中范围解析运算符的作用及使用
深入解析C++编程中范围解析运算符的作用及使用
摘要:范围解析运算符::用于标识和消除在不同范围内使用的标识符。语法复制代码代码如下:::identifierclass-name::identi...

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

语法

复制代码 代码如下:

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

备注

identifier 可以是变量、函数或枚举值。

具有命名空间和类

以下示例显示范围解析运算符如何与命名空间和类一起使用:

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; }

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

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。

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。

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 ; }

具有静态成员

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

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(); }

具有区分范围的枚举

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

enum class EnumA{ First, Second, Third }; int main() { EnumA enum_value = EnumA::First; }

【深入解析C++编程中范围解析运算符的作用及使用】相关文章:

从汇编看c++中extern关键字的使用

解析C语言中如何正确使用const

解析C++中虚析构函数的作用

浅析C++中前置声明的应用与陷阱

深入解析C语言中常数的数据类型

深入解析C++中的引用类型

深入C++中inline关键字的使用

深入解析C++中的构造函数和析构函数

深入分析C++中类的大小

深入理解结构体中占位符的用法

精品推荐
分类导航