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

Regular cast vs static_cast vs dynamic_cast ใน C++


static_cast

ใช้สำหรับ type conversion ธรรมดา/ปกติ (ordinary) เช่น float → int, char → int รับผิดชอบ implicit coercion ด้วย

dynamic_cast

ใช้สำหรับ polymorphism เฉพาะการ cast จาก base class ไป derived class (downcasting) ตรวจสอบ runtime (ต้องมี virtual function)

Regular Cast (C-style cast)

รูปแบบ (Type)expr หรือ Type(expr) อันทรงพลังที่สุด รวม const_cast, static_cast, reinterpret_cast แต่ ไม่ใช้ dynamic_cast ไม่ปลอดภัย

Cast อื่นๆ

  • const_cast: เพิ่ม/ลบ const qualifier
  • reinterpret_cast: ตีความ bit pattern ใหม่ ระดับต่ำมาก (low-level) ใช้กับ raw data, pointer manipulation