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