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