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

ความหมายของ Double Colon :: นำหน้าใน C++


Double Colon (::) หรือ Scope Resolution Operator

Double colon นำหน้าเรียกว่า Scope Resolution Operator มีการใช้งานหลักดังนี้

1. กำหนดฟังก์ชันนอกคลาส

ใช้กำหนดฟังก์ชันภายนอกคลาส

ตัวอย่าง

#include <iostream>
using namespace std;

class Example {
    int num;
public:
    Example() { num = 10; }
    void display();
};

void Example::display() {
    cout << "The value of num is: " << num;
}

int main() {
    Example obj;
    obj.display();
    return 0;
}

ผลลัพธ์

The value of num is: 10

2. เข้าถึง global variable เมื่อมี local variable ชื่อเดียวกัน

ใช้ :: เพื่อเข้าถึง global variable ที่ถูกบังโดย local variable

ตัวอย่าง

#include <iostream>
using namespace std;

int num = 7;
int main() {
    int num = 3;
    cout << "Value of local variable num is: " << num;
    cout << "\nValue of global variable num is: " << ::num;
    return 0;
}

ผลลัพธ์

Value of local variable num is: 3
Value of global variable num is: 7