Scope resolution operator là gì?

Noun C++
Toán tử phân giải phạm vi

Trong C++, toán tử phân giải phạm vi (scope resolution operator) là ::. Nó được sử dụng cho các mục đích sau:

1) Để truy cập một biến toàn cục (global variable) khi có một biến cục bộ (local variable) có cùng tên:


#include<iostream>
using namespace std;
   
int x;  // Global x
   
int main()
{
  int x = 10; // Local x
  cout 

Output:

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

2) Để định nghĩa một hàm (function) bên ngoài một lớp (class).


#include<iostream>
using namespace std;
  
class A 
{
public: 
  
   // Only declaration
   void fun();
};
  
// Definition outside class using ::
void A::fun()
{
   cout 

Output:

fun() called

3) Truy cập các biến tĩnh (static variable) của một lớp.


#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 

Output:

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

4) Trong trường hợp đa kế thừa (multiple inheritance):

Nếu cùng một tên biến tồn tại trong hai lớp cha (ancestor class), chúng ta có thể sử dụng toán tử phân giải phạm vi (scope resolution operator) để phân biệt.


#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 

Output:

A's x is 10
B's x is 20
Test::y = 2;

5) Đối với namespace

Nếu một lớp có cùng tên tồn tại bên trong hai namespace, chúng ta có thể sử dụng tên namespace với toán tử phân giải phạm vi (scope resolution operator) để tham chiếu đến lớp đó mà không có bất kỳ xung đột nào


#include<iostream>
  
  
int main(){
    std::cout 

Output:

Here, cout and endl belong to the std namespace.

6) Tham chiếu đến một lớp bên trong một lớp khác:

Nếu một lớp tồn tại bên trong một lớp khác, chúng ta có thể sử dụng lớp bên ngoài (nesting class) để tham chiếu lớp bên trong (nested class) bằng cách sử dụng toán tử phân giải phạm vi (scope resolution operator).


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

Learning English Everyday