当前位置:   article > 正文

C++作用域运算符“::“的作用_c++ 作用运算符“::”的功能是

c++ 作用运算符“::”的功能是
1: 当存在具有相同名称的局部变量时,要访问全局变量
#include<iostream>  
using namespace std; 
 
int x;  // Global x 
 
int main() 
{ 
  int x = 10; // Local x 
  cout << "Value of global x is " << ::x; 
  cout << "\nValue of local x is " << x;   
  return 0; 
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
2: 在类之外定义函数
#include<iostream>  
using namespace std; 
 
class A  
{ 
public:  
 
   // Only declaration 
   void fun(); 
}; 
 
// Definition outside class using :: 
void A::fun() 
{ 
   cout << "fun() called"; 
} 
 
int main() 
{ 
   A a; 
   a.fun(); 
   return 0; 
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
3:访问一个类的静态变量
#include<iostream> 
using namespace std; 
 
class Test 
{ 
    static int x;   
public: 
    static int y;    
 
    // Local parameter 'a' hides class member 
    // 'a', but we can access it using :: 
    void func(int x)   
    {  
       // We can access class's static variable 
       // even if there is a local variable 
       cout << "Value of static x is " << Test::x; 
 
       cout << "\nValue of local x is " << x;   
    } 
}; 
 
// In C++, static members must be explicitly defined  
// like this 
int Test::x = 1; 
int Test::y = 2; 
 
int main() 
{ 
    Test obj; 
    int x = 3 ; 
    obj.func(x); 
 
    cout << "\nTest::y = " << Test::y; 
 
    return 0; 
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
4: 如果有多个继承, 使用作用域运算符进行区分
#include<iostream> 
using namespace std; 
 
class A 
{ 
protected: 
    int x; 
public: 
    A() { x = 10; } 
}; 
 
class B 
{ 
protected: 
    int x; 
public: 
    B() { x = 20; } 
}; 
 
class C: public A, public B 
{ 
public: 
   void fun() 
   { 
      cout << "A's x is " << A::x; 
      cout << "\nB's x is " << B::x; 
   } 
}; 
 
int main() 
{ 
    C c; 
    c.fun(); 
    return 0; 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
5: 使用嵌套类使用作用域运算符来引用嵌套的类
#include<iostream> 
using namespace std; 
 
class outside 
{ 
public: 
      int x; 
      class inside 
      { 
      public: 
            int x; 
            static int y;  
            int foo(); 
 
      }; 
}; 
int outside::inside::y = 5;  
 
int main(){ 
    outside A; 
    outside::inside B; 
 
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号