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

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

ที่นี่เราจะดูตัวอย่าง C++ และลองดูว่าจะได้ผลลัพธ์อะไร จากนั้นจะเข้าใจวัตถุประสงค์และการทำงานของ scope resolution operator และ 'this' pointer ใน C++

ถ้าโค้ดมีสมาชิกชื่อ 'x' และเราต้องการใช้ฟังก์ชันอื่นที่รับอาร์กิวเมนต์ชื่อเดียวกัน 'x' ภายในฟังก์ชันนั้น ถ้าใช้ 'x' จะซ่อนตัวแปรสมาชิก และใช้ตัวแปรท้องถิ่นแทน มาลองดูในโค้ดนี้

ตัวอย่างที่ 1: ไม่ใช้ this หรือ ::

#include <iostream>
using namespace std;

class MyClass {
private:
    int x;
public:
    MyClass(int y) { x = y; }
    void myFunction(int x) {
        cout << "Value of x is: " << x;
    }
};

int main() {
    MyClass ob1(10);
    ob1.myFunction(40);
}

ผลลัพธ์

Value of x is: 40

เพื่อเข้าถึง x ของคลาส ต้องใช้ 'this' pointer 'this' เป็น pointer พิเศษชี้ไปที่ออบเจ็กต์ปัจจุบัน

ตัวอย่างที่ 2: ใช้ this pointer

#include <iostream>
using namespace std;

class MyClass {
private:
    int x;
public:
    MyClass(int y) { x = y; }
    void myFunction(int x) {
        cout << "Value of x is: " << this->x;
    }
};

int main() {
    MyClass ob1(10);
    ob1.myFunction(40);
}

ผลลัพธ์

Value of x is: 10

ใน C++ มีอีกออปอเรเตอร์ชื่อ scope resolution operator ใช้เข้าถึงสมาชิกของคลาสพาเรนต์หรือ static members ถ้าใช้ scope resolution operator สำหรับ instance member จะไม่ได้ผล ทำนองเดียวกัน ถ้าใช้ 'this' pointer สำหรับ static member จะมีปัญหา

ตัวอย่างที่ 3: ใช้ :: สำหรับ static member

#include <iostream>
using namespace std;

class MyClass {
    static int x;
public:
    void myFunction(int x) {
        cout << "Value of x is: " << MyClass::x;
    }
};

int MyClass::x = 50;

int main() {
    MyClass ob1;
    ob1.myFunction(40);
}

ผลลัพธ์

Value of x is: 50