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

Scope Resolution Operator เทียบ this Pointer ใน C++

Scope Resolution Operator ใช้เข้าถึงสมาชิก static หรือของคลาส ในขณะที่ this pointer ใช้เข้าถึงสมาชิกของออบเจ็กต์เมื่อมีตัวแปรท้องถิ่นชื่อเดียวกัน

Scope Resolution Operator

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

#include <iostream>
using namespace std;

class AB {
    static int x;
public:
    // พารามิเตอร์ท้องถิ่น 'x' ซ่อนสมาชิกคลาส 'x' แต่เราสามารถเข้าถึงได้ด้วย ::
    void print(int x) {
        cout << "the number is: " << AB::x;
    }
};

// สมาชิก static ต้องกำหนดค่าเริ่มต้นอย่างชัดเจนใน C++
int AB::x = 7;

int main() {
    AB ob;
    int m = 6;
    ob.print(m);
    return 0;
}

ผลลัพธ์

the number is: 7

this Pointer

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

#include <iostream>
using namespace std;

class AB {
    int x;
public:
    AB() {
        x = 6;
    }
    // พารามิเตอร์ท้องถิ่น 'x' ซ่อนสมาชิกออบเจ็กต์ 'x' เราเข้าถึงได้ด้วย this
    void print(int x) {
        cout << "the number is: " << this->x;
    }
};

int main() {
    AB ob;
    int m = 7;
    ob.print(m);
    return 0;
}

ผลลัพธ์

the number is: 6