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*'