Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ตัวดำเนินการ Scope Resolution (::) ใน C++

ตัวดำเนินการ Scope Resolution (::) ใช้หลายวัตถุประสงค์:

  • เข้าถึงตัวแปร Global เมื่อชื่อซ้ำกับตัวแปร Local
  • นิยามฟังก์ชันนอกคลาส
  • เข้าถึง Static Members ของคลาส

ตัวอย่างโค้ด

#include <iostream>
using namespace std;

char a = 'm';
static int b = 50;

int main() {
    char a = 's';
    cout << "The static variable : " << ::b;
    cout << "\nThe local variable : " << a;
    cout << "\nThe global variable : " << ::a;
    return 0;
}

ผลลัพธ์

The static variable : 50
The local variable : s
The global variable : m

ในตัวอย่าง: ::b เข้าถึง static variable ระดับไฟล์ ::a เข้าถึง global variable a ขณะที่ a เพียงอย่างเดียวเข้าถึง local variable