當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ static_cast用法及代碼示例

Cast 運算符是一元運算符,它強製將一種數據類型轉換為另一種數據類型。

C++ 支持 4 種類型的轉換:

  1. 靜態投射
  2. Dynamic _Cast
  3. 常量演員表
  4. 重新詮釋演員陣容

本文重點詳細討論static_cast。

靜態投射

這是可以使用的最簡單的轉換類型。這是一個編譯時轉換。它執行類型之間的隱式轉換(例如 int 到 float,或指向 void* 的指針)之類的操作,並且還可以調用顯式轉換函數。

static_cast 的語法

static_cast <dest_type> (source);

static_cast的返回值為dest_type。

static_cast 的示例

下麵是實現static_cast的C++程序:

C++


// C++ Program to demonstrate
// static_cast
#include <iostream>
using namespace std;
// Driver code
int main()
{
    float f = 3.5;
    // Implicit type case
    // float to int
    int a = f;
    cout << "The Value of a: " << a;
    // using static_cast for float to int
    int b = static_cast<int>(f);
    cout << "\nThe Value of b: " << b;
}
輸出
The Value of a: 3
The Value of b: 3

static_cast在不同場景下的行為

1. static_cast 用於基本數據類型指針:

現在讓我們對上麵的代碼進行一些更改。

C++


// C++ Program to demonstrate 
// static_cast char* to int*
#include <iostream>
using namespace std;
// Driver code
int main()
{
  int a = 10;
  char c = 'a';
   
  // Pass at compile time, 
  // may fail at run time
  int* q = (int*)&c;
  int* p = static_cast<int*>(&c);
  return 0;
}

輸出

error: invalid 'static_cast' from type 'int*' to type 'char*'

說明:這意味著即使您認為可以以某種方式將特定對象指針類型轉換為另一個對象指針,但這是非法的,static_cast 也不允許您這樣做。

2. 使用用戶定義的轉換運算符轉換對象

static_cast 能夠調用該類的conversion operator(如果已定義)。讓我們再舉一個將對象與類相互轉換的例子。

例子:

C++


// C++ Program to cast
// class object to string
// object
#include <iostream>
#include <string>
using namespace std;
// new class
class integer {
    int x;
public:
    // constructor
    integer(int x_in = 0)
        : x{ x_in }
    {
        cout << "Constructor Called" << endl;
    }
    // user defined conversion operator to string type
    operator string()
    {
        cout << "Conversion Operator Called" << endl;
        return to_string(x);
    }
};
// Driver code
int main()
{
    integer obj(3);
    string str = obj;
    obj = 20;
    // using static_cast for typecasting
    string str2 = static_cast<string>(obj);
    obj = static_cast<integer>(30);
    return 0;
}
輸出
Constructor Called
Conversion Operator Called
Constructor Called
Conversion Operator Called
Constructor Called

解釋:讓我們嘗試逐行理解上麵的輸出:

  1. 什麽時候對象創建後,調用構造函數,在我們的例子中,它也是一個轉換構造函數(對於 C++14 規則進行了一些更改)。
  2. 當你創建時str在......之外對象,編譯器不會拋出錯誤,因為我們已經定義了轉換運算符。
  3. 當你做對象=20,您實際上正在調用轉換構造函數。
  4. 當你做str2在......之外static_cast,它與字符串非常相似字符串 = 對象;但有嚴格的類型檢查。
  5. 當你寫的時候obj = static_cast <整數> (30),您將 30 轉換為整數使用static_cast。

3.static_cast用於C++中的繼承

static_cast在繼承的情況下可以提供向上轉型和向下轉型。以下示例演示了在向上轉換的情況下使用static_cast。

例子:

C++


// C++ Program to demonstrate 
// static_cast in inheritance
#include <iostream>
using namespace std;
class Base 
{};
class Derived : public Base 
{};
// Driver code
int main()
{
  Derived d1;
   
  // Implicit cast allowed
  Base* b1 = (Base*)(&d1);
   
  // upcasting using static_cast
  Base* b2 = static_cast<Base*>(&d1);
  return 0;
}

說明:上麵的代碼將編譯,沒有任何錯誤。

  1. 我們獲取 d1 的地址並將其顯式轉換為 Base 並將其存儲在 b1 中。
  2. 我們獲取 d1 的地址並使用 static_cast 將其轉換為 Base 並將其存儲在 b2 中。

在上麵的例子中,我們繼承了public基類。當我們將其繼承為私有時會發生什麽?下麵的示例演示了以下內容:

例子:

C++


// C++ program to demonstrate 
// static_cast in case of 
// private inheritance
#include <iostream>
using namespace std;
class Base 
{};
class Derived: private Base 
{ 
  // Inherited private/protected 
  // not public
};
// Driver code
int main()
{    
  Derived d1;
   
  // Implicit type cast allowed
  Base* b1 = (Base*)(&d1);
   
  // static_cast not allowed
  Base* b2 = static_cast<Base*>(&d1);
  return 0;
}

編譯時錯誤:

[Error] 'Base' is an inaccessible base of 'Derived'

說明:即使您將其繼承為受保護的,上麵的代碼也不會編譯。

So to use static_cast in case of inheritance, the base class must be accessible, non virtual and unambiguous.

4. static_cast 投射“往返”空指針

static_cast 運算符允許從任何指針類型轉換為 void 指針,反之亦然。

例子:

C++


// C++ program to demonstrate 
// static_cast to cast 'to and 
// from' the void pointer
#include <iostream>
using namespace std;
// Driver code
int main()
{
  int i = 10;
  void* v = static_cast<void*>(&i);
  int* ip = static_cast<int*>(v);
  cout << *ip;
  return 0;
}
輸出
10


相關用法


注:本文由純淨天空篩選整理自amanrk92大神的英文原創作品 static_cast in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。