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

Const Cast ใน C++

บทนำ

งานนี้แสดงการทำงานของ const_cast ใน C++

const_cast เป็นหนึ่งใน Type Casting Operators ใช้เปลี่ยนค่าคงที่ (Constant Value) ของออบเจ็กต์ หรือพูดง่ายๆ คือเอาคุณสมบัติ Constant ออกจากออบเจ็กต์

const_cast ใช้ในโปรแกรมที่มีออบเจ็กต์ค่าคงที่ที่ต้องเปลี่ยนแปลงบ้างในบางจุด

Syntax

const_cast<type name>(expression)

ตัวอย่าง

Input: x = 50
const int* y = &x
cout << "old value is" << *y << "\n";
int* z = const_cast<int*>(y);
*z = 100;
cout << "new value is" << *y;
Output: old value is 50
        new value is 100

ตัวอย่างแสดงการใช้งานพื้นฐาน: ประกาศตัวแปรคงที่ x = 50 และ pointer คงที่ y ชี้ x สร้าง pointer ที่ 3 (z) ใช้ const_cast กับ y แล้วกำหนดค่าให้ z จึงเปลี่ยนค่าที่ y ชี้ได้

ถ้าไม่ใช้ const_cast และพยายามเปลี่ยนค่า x ผ่าน y จะได้ Error: "assignment of read-only location"

แนวทางในโปรแกรม

  • สร้างตัวแปรคงที่ int a = 20
  • สร้าง pointer คงที่ b ชี้ &a
  • สร้าง pointer c แบบปกติ ใช้ const_cast กับ b
  • เปลี่ยนค่า *c = 40 → ค่าที่ b ชี้เปลี่ยนตาม

อัลกอริทึม

Start
Step 1 → In main()
    Declare const int a = 20
    Declare const int* b = &a
    Declare int* c = const_cast<int*>(b)
    Assign *c = 40
Stop

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

#include <iostream>
using namespace std;

int main() {
    const int a = 20;
    const int* b = &a;
    cout << "old value is" << *b << "\n";
    int* c = const_cast<int*>(b);
    *c = 40;
    cout << "new value is" << *b;
    return 0;
}

ผลลัพธ์

old value is 20
new value is 40

Pointer คงที่ b ชี้ a = 20 ซึ่งเปลี่ยนไม่ได้ แต่สร้าง pointer c แบบไม่คงที่ ใช้ const_cast จึงเปลี่ยนค่าได้

การใช้งานอื่นของ const_cast

ใช้ส่งข้อมูลคงที่ไปฟังก์ชันที่ไม่รับข้อมูลคงที่

ตัวอย่าง

#include <iostream>
using namespace std;

int change(int* p2) {
    return (*p2 * 10);
}

int main() {
    const int num = 100;
    const int* p = &num;
    int* p1 = const_cast<int*>(p);
    cout << change(p1);
    return 0;
}

ผลลัพธ์

1000

ส่งค่าคงที่ 100 ผ่าน const_cast ให้ change() ซึ่งไม่รับ const ฟังก์ชันคูณ 10 คืน 1000

ถ้าไม่ใช้ const_cast จะ Compile Error