C++ 中的 static_cast
static_cast 用于常规类型转换。这也是负责隐式类型转换并可以显式调用的转换。你应在将浮点数转换为整数、将字符转换为整数等情况下使用它。它可以转换相关类型类。
举例
#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*'
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP