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 祝产妇的祝福语简短