跳轉到內容

更多 C++ 慣用法/隱式轉換

來自 Wikibooks,開放世界中的開放書籍

隱式轉換

[編輯 | 編輯原始碼]

注意
文章需要改進!

當某個型別 T1 的表示式用在不接受該型別但接受其他型別 T2 的上下文中時,就會執行隱式轉換。

也稱為

[編輯 | 編輯原始碼]

在某些上下文中,可以使用與函式所需型別不完全相同的變數。特別是

  • 當表示式用作呼叫以 T2 作為引數宣告的函式時的引數時;
  • 當表示式用作期望 T2 的運算子的運算元時;
  • 當初始化型別為 T2 的新物件時,包括在返回 T2 的函式中的 return 語句;
  • 當表示式用在 switch 語句中時(T2 為整型);
  • 當表示式用在 if 語句或迴圈中時(T2 為 bool)。

只有當從 T1 到 T2 存在一個明確的隱式轉換序列時,程式才是格式良好的(可以編譯)。

更多資訊:C++ 參考 en.cppreference.com implicit_conversion

解決方案和示例程式碼

[編輯 | 編輯原始碼]

指標到布林的轉換

int a = 42;
int* ptr = &a;
if (ptr) // checks if ptr is not null_ptr
   ...

std::string 到其他型別的轉換

#include <string>

struct A {
    A( const std::string & s ) {}
};

void func( const A & a ) {
}

int main() {
    func( "one" );               // error - requires 2 steps to convert: const char* -> std::string -> A
    func( A("two") );            // ok - converting const char* -> std::string, which is used to create A
    func( std::string("three") );// ok - implicit conversion std::string -> A
}

示例來自這個 Stack Overflow 問題,標題為:C++ 隱式轉換。

已知用途

[編輯 | 編輯原始碼]

到處都是,一直都是,...

[編輯 | 編輯原始碼]

參考文獻

[編輯 | 編輯原始碼]
華夏公益教科書