作用域运算符
global scope(全局作用域符),用法(::name)
class scope(类作用域符),用法(class::name)
namespace scope(命名空间作用域符),用法(namespace::name)
他们的作用都是为了更明确的调用你想要的变量。:: 如果前面有东西那么一定是命名空间名或者是类名。
#include <iostream>using namespace std;int count = 0;struct FHello {static const int count = 10;};void main() {int count = 20;cout << count << endl;cout << ::count << endl;cout << FHello::count << endl;}// 20// 10// 0
相当于在类的定义里定义一个静态变量/函数,那么这个变量就属于这个类了,需要加上 :: 才可以访问到。或者通过对象来访问也可以。编译器编译时,全部会替换类名调用。
#include <iostream>using namespace std;struct FHello {static void hello() {cout << "213" << endl;};static const int count = 10;};int main() {FHello Hello;Hello.hello();cout << Hello.count << endl;}
作用域也是有当前作用域的,例如在类中可以忽略 FHello::a 来访问 a 。
struct FHello {static int hello() {return a + b;};static int a;static int b;};
通过类名来定义指针
struct Student {int a;int b;float c;}int main() {Student wang {1, 2, 3.0};int Student::*p = &Student::a;wang.*p = 1;return 0;}
看一个指针指向什么要看解引用后表示什么东西,p 解引用后表示 Student 类型中的 int 成员,因此 p 指向的是 Student 类中的 int 成员。
类似的有 int (*q)[5]q 解引用后表示长度为 5 的 int 数组。
菱形继承中的 ::
上面讲的主要是静态变量/函数,接下来我们看 :: 在普通成员中的使用。
#include <iostream>using namespace std;class A {public:int m_a = 1;};class B :public A {public:int m_b;};class C :public A {public:int m_c;};class D :public B, public C {public:void hello() {cout << B::m_a << endl;}};int main() {D d;d.hello();return 0;}
使用 :: 来解决继承中的冲突。
