C ++中的static_cast
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*'
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志