ที่นี่เราจะดูว่าคำหลักที่เปลี่ยนแปลงได้ใน C ++ คืออะไร การเปลี่ยนแปลงเป็นหนึ่งในคลาสการจัดเก็บใน C ++ สมาชิกข้อมูลที่เปลี่ยนแปลงได้เป็นสมาชิกประเภทนั้น ซึ่งสามารถเปลี่ยนแปลงได้ตลอดเวลา แม้ว่าวัตถุจะเป็นประเภท const เมื่อเราต้องการสมาชิกเพียงตัวเดียวเป็นตัวแปรและอีกตัวหนึ่งเป็นค่าคงที่ เราก็สามารถทำให้พวกมันกลายพันธุ์ได้ มาดูตัวอย่างกันเพื่อให้ได้แนวคิด
ตัวอย่าง
#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 is constant, but data will be changed
this->y = y;
}
void display() const{
cout<<endl<<"(x: "<<x<<" y: "<<y << ")"<<endl;
}
};
int main(){
const MyClass s(15,25); // A const object
cout<<endl <<"Before Change: ";
s.display();
s.setx(150);
s.sety(250);
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)