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

คีย์เวิร์ด Mutable ใน C++ คืออะไร?

ที่นี่เราจะดูว่า mutable keyword ใน C++ คืออะไร mutable เป็นหนึ่งใน storage class ใน C++ สมาชิกข้อมูล mutable เป็นสมาชิกที่สามารถเปลี่ยนแปลงได้ตลอดเวลา แม้ว่าออบเจ็กต์จะเป็น const type เมื่อเราต้องการให้สมาชิกเพียงตัวเดียวเป็นตัวแปรและอีกตัวเป็นค่าคงที่ เราสามารถทำให้มันเป็น mutable ได้ มาดูตัวอย่างเพื่อเข้าใจแนวคิด

ตัวอย่าง

#include <iostream>
using namespace std;

class MyClass {
    int x;
    mutable int y;
public:
    MyClass(int x = 0, int y = 0) {
        this->x = x;
        this->y = y;
    }
    void setx(int x = 0) {
        this->x = x;
    }
    void sety(int y = 0) const { // member function เป็น const แต่ข้อมูลจะเปลี่ยนได้
        this->y = y;
    }
    void display() const {
        cout << endl << "(x: " << x << " y: " << y << ")" << endl;
    }
};

int main() {
    const MyClass s(15, 25); // ออบเจ็กต์ const
    cout << endl << "Before Change: ";
    s.display();
    s.setx(150); // จะเกิด error เพราะ setx ไม่ใช่ const
    s.sety(250); // ทำงานได้ เพราะ sety เป็น const และ y เป็น mutable
    cout << endl << "After Change: ";
    s.display();
}

ผลลัพธ์ (ถ้ารันโค้ดเต็ม)

[Error] passing 'const MyClass' as 'this' argument of 'void MyClass::setx(int)' discards qualifiers [-fpermissive]

ถ้าเราลบบรรทัด s.setx(150); ออก แล้วรัน:

ผลลัพธ์

Before Change: (x: 15 y: 25)
After Change: (x: 15 y: 250)