📜  C++中的范围解析运算符

📅  最后修改于: 2021-05-30 19:49:47             🧑  作者: Mango

在C++中,范围解析运算符为:: 。它用于以下目的。

1)当存在具有相同名称的局部变量时,要访问全局变量:

// C++ program to show that we can access a global variable
// using scope resolution operator :: when there is a local 
// variable with same name 
#include 
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;
}

输出:

Value of global x is 0
Value of local x is 10

2)在类外定义函数。

// C++ program to show that scope resolution operator :: is used
// to define a function outside a class
#include 
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;
}

输出:

fun() called

3)访问一个类的静态变量。

// C++ program to show that :: can be used to access static
// members when there is a local variable with same name
#include
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;
}

输出:

Value of static x is 1
Value of local x is 3
Test::y = 2;

4)如果是多重继承:
如果两个祖先类中存在相同的变量名,则可以使用范围解析运算符进行区分。

// Use of scope resolution operator in multiple inheritance.
#include
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;
}

输出:

A's x is 10
B's x is 20

5)对于命名空间
如果两个名称空间中都存在具有相同名称的类,则可以将名称空间名称与作用域解析运算符来引用该类,而不会发生任何冲突

// Use of scope resolution operator for namespace.
#include
  
  
int main(){
    std::cout << "Hello" << std::endl;
  
}
Here, cout and endl belong to the std namespace.

6)引用另一个类中的一个类:
如果一个类存在于另一个类中,则可以使用范围解析运算符使用嵌套类来引用嵌套类

// Use of scope resolution class inside another class.
#include
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;
  
}
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”