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

更新於:2019-07-30

4K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.