static_cast ใช้สำหรับการแปลงประเภทปกติ/ธรรมดา นี่ยังเป็นนักแสดงที่รับผิดชอบสำหรับการบีบบังคับแบบโดยปริยายและยังสามารถเรียกได้อย่างชัดเจน คุณควรใช้ในกรณีเช่นการแปลง float เป็น int, char เป็น int เป็นต้น ซึ่งสามารถสร้างคลาสที่เกี่ยวข้องได้
ตัวอย่าง
#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
หากประเภทไม่เหมือนกันจะทำให้เกิดข้อผิดพลาดบางอย่าง
ตัวอย่าง
#include<iostream>
using namespace std;
class Base {};
class Derived : public Base {};
class MyClass {};
main(){
Derived* d = new Derived;
Base* b = static_cast<Base*>(d); // this line will work properly
MyClass* x = static_cast<MyClass*>(d); // ERROR will be generated during
compilation
} ผลลัพธ์
[Error] invalid static_cast from type 'Derived*' to type 'MyClass*'