คำอธิบาย
ที่นี่เราจะดูว่ามีเทคนิคการแปลงชนิดข้อมูล (type conversion) อะไรบ้างใน C++ มีหลักๆ 2 ประเภท คือ Implicit (โดยนัย) และ Explicit (แสดงออกชัดเจน)
Implicit type conversion (การแปลงชนิดโดยนัย)
นี้ còn เรียกว่า automatic type conversion การแปลงนี้ทำโดยคอมไพเลอร์โดยอัตโนมัติโดยไม่มีการกระตุ้นจากผู้ใช้ เกิดขึ้นเมื่อนิพจน์ (expression) มีชนิดข้อมูลมากกว่าหนึ่งชนิด
ชนิดข้อมูลทั้งหมดจะถูกอัปเกรดเป็นชนิดข้อมูลของตัวแปรที่ใหญ่ที่สุด
bool -> char -> short int -> int -> unsigned int -> long -> unsigned long -> long long -> float -> double -> long double
ในการแปลงโดยนัย อาจสูญเสียข้อมูลบางส่วน เช่น sign อาจหายไป
ตัวอย่าง
#include <iostream> using namespace std; int main() { int a = 10; char b = 'a'; a = b + a; float c = a + 1.0; cout << "a : " << a << "\nb : " << b << "\nc : " << c; }ผลลัพธ์
a : 107 b : a c : 108
Explicit type conversion (การแปลงชนิดอย่างชัดเจน / Type Casting)
นี่ còn เรียกว่า type casting ที่นี่ผู้ใช้สามารถแปลงชนิดผลลัพธ์ให้เป็นชนิดข้อมูลเฉพาะได้ ใน C++ เราสามารถทำได้ 2 วิธี คือ ใช้ expression ในวงเล็บ หรือใช้ static_cast หรือ dynamic_cast
ตัวอย่าง
#include <iostream> using namespace std; int main() { double x = 1.574; int add = (int)x + 1; cout << "Add: " << add; float y = 3.5; int val = static_cast<int>(y); cout << "\nvalue: " << val; }ผลลัพธ์
Add: 2 value: 3