บทนำ
งานนี้แสดงการทำงานของ const_cast ใน C++
const_cast เป็นหนึ่งใน Type Casting Operators ใช้เปลี่ยนค่าคงที่ของออบเจ็กต์ หรือเอาคุณสมบัติ Constant ออก
ใช้ในโปรแกรมที่มีออบเจ็กต์ค่าคงที่ที่ต้องเปลี่ยนแปลงบ้างในบางจุด
Syntax
const_cast<type name>(expression)
ตัวอย่าง
Input: const int 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 z ใช้ const_cast กับ y แล้วกำหนดค่า z ได้ค่าที่ y ชี้เปลี่ยน
ถ้าไม่ใช้ const_cast จะ Error: "assignment of read-only location"
ตัวอย่างเพิ่มเติม
Input: const int 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
แนวทางในโปรแกรม
- สร้างตัวแปรคงที่ int a = 20
- สร้าง pointer คงที่ b ชี้ &a
- สร้าง pointer c ใช้ const_cast
- ส่ง b เข้า const_cast กำหนดให้ c
- เปลี่ยนค่า *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
ตัวอย่าง
#include <iostream>
using namespace std;
int change(int* p2) {
return (*p2 * 10);
}
int main() {
const int num = 100;
const int* p = #
int* p1 = const_cast<int*>(p);
cout << change(p1);
return 0;
}
ผลลัพธ์
1000
ส่งค่าคงที่ 100 ผ่าน const_cast ให้ change() คูณ 10 ได้ 1000
ไม่ใช้ const_cast จะ Compile Error