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

Casting Operators ใน C++


นิยาม

Cast เป็น special operator บังคับแปลงชนิดข้อมูล เป็น unary operator precedence เท่ากับ unary operators อื่นๆ

รูปแบบทั่วไป (C-style cast)

(type) expression

C++ Casting Operators (เฉพาะเจาะจงกว่า)

Operatorวัตถุประสงค์
const_cast<type>(expr)Override const/volatile attributes เปลี่ยน const-ness เท่านั้น
dynamic_cast<type>(expr)Runtime cast ตรวจสอบความถูกต้อง ล้มเหลวคืน null ใช้กับ polymorphic types
reinterpret_cast<type>(expr)แปลง pointer เป็น pointer อื่น หรือ pointer ↔ integer
static_cast<type>(expr)Non-polymorphic cast เช่น base* → derived*

ตัวอย่าง C-style Cast

#include <iostream>
using namespace std;

int main() {
    double a = 21.09399;
    float b = 10.20;
    int c;

    c = (int)a;
    cout << "Line 1 - (int)a: " << c << endl;

    c = (int)b;
    cout << "Line 2 - (int)b: " << c << endl;
    return 0;
}

ผลลัพธ์

Line 1 - (int)a: 21
Line 2 - (int)b: 10

ส่วนทศนิยมถูกตัดทิ้ง (truncation)