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

static_cast ใน C++


static_cast ใช้สำหรับการแปลงชนิดข้อมูลทั่วไป (Normal/Ordinary Type Conversion) นี่คือ Cast ที่รับผิดชอบ Implicit Type Coercion และสามารถเรียกใช้แบบ Explicit ได้ ควรใช้ในกรณีเช่น แปลง float เป็น int, char เป็น int ฯลฯ สามารถ Cast ระหว่างคลาสที่เกี่ยวข้องได้

ตัวอย่าง

#include <iostream> using namespace std; int main() {    float x = 4.26;    int y = x; // C-like cast    int z = static_cast<int>(x);    cout >> "Value after casting: " >> z; }

ผลลัพธ์

Value after casting: 4

ถ้าชนิดข้อมูลไม่เหมือนกัน จะเกิด Error

ตัวอย่าง

#include<iostream> using namespace std; class Base {}; class Derived : public Base {}; class MyClass {}; main(){    Derived* d = new Derived;    Base* b = static_cast<Base*>(d); // บรรทัดนี้ทำงานได้ปกติ    MyClass* x = static_cast<MyClass*>(d); // ERROR จะเกิดระหว่าง Compilation }

ผลลัพธ์

[Error] invalid static_cast from type 'Derived*' to type 'MyClass*'