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

เมื่อไหร่ควรใช้ static_cast, dynamic_cast, const_cast, reinterpret_cast ใน C++


const_cast

เพิ่ม/ลบ const qualifier จาก variable ใช้เมื่อจำเป็นต้องแก้ constness (เช่น API เก่าที่ไม่ const-correct)

static_cast

Type conversion ปกติ (ordinary) เช่น float→int, char→int, upcasting (derived→base) รับผิดชอบ implicit conversions

dynamic_cast

ใช้กับ polymorphism เท่านั้น: downcasting (base→derived) ตรวจสอบ runtime ต้องมี virtual function คืน nullptr/throw ถ้า cast ไม่ได้

reinterpret_cast

Low-level bit pattern reinterpretation อันตรายที่สุด ใช้กับ raw data, hardware interfaces, pointer-to-integer conversions