• <table id="4yyaw"><kbd id="4yyaw"></kbd></table>
  • <td id="4yyaw"></td>
  • 發布時間:2020-09-28 23:09 原文鏈接: C++之類型轉換函數(五)

    輸出結果:

    root@txp-virtual-machine:/home/txp# g++ test.cpp
    test.cpp: In function ‘int main()’:
    test.cpp:21:8: error: no match for ‘operator=’ (operand types are ‘Test’ and ‘int’)
         t =6;
           ^
    test.cpp:21:8: note: candidate is:
    test.cpp:4:7: note: Test& Test::operator=(const Test&)
    class Test{
          ^
    test.cpp:4:7: note:   no known conversion for argument 1 from ‘int’ to ‘const Test&’

    注解:這里顯示不能這樣轉換

    代碼實踐二(進行顯示轉換):

    #include <iostream>
    #include <string>
    class Test{
    public:
       Test()
       {
       }
      explicit Test(int i)
       {
       }
    };
    int main()
    {
        Test t;
        t =static_cast<Test>(6);
        return 0;
    }

    輸出結果(編譯通過):

    root@txp-virtual-machine:/home/txp# g++ test.cpp
    root@txp-virtual-machine:/home/txp#

    4、小結:

    轉換構造函數只有一個參數

    轉換構造函數的參數類型是其它類型

    轉換構造函數在類型轉換時被調用

    隱式類型轉換是工程中bug的重要來源

    explicit關鍵字用于杜絕隱式類型轉換

    二、類型轉換函數:

    1、類類型轉換普通類型:

    在我們上面通過代碼測試發現不行,那么是真的不行嗎,事實是可以進行轉換的,不過要用到我們現在c++里面的類型轉換函數(它用于將類對象轉換為其它類型),類型轉換的語法如下:

    operator Type()
    {
       Type ret;
       
       return ret;
    }

    代碼實踐:

    #include <iostream>
    #include <string>
    class Test{
    public:
       Test()
       {
       }
      operator int()
      {
       }
    };
    int main()
    {
        Test t;
        int i =t;
        return 0;
    }

    輸出結果(編譯沒有報錯):

    root@txp-virtual-machine:/home/txp# g++ test.cpp
    root@txp-virtual-machine:/home/txp#

    注:

    與轉換構造函數具有同等的地位

    使得編譯器有能力將對象轉化為其它類型

    編譯器能夠隱式的使用類型轉換函數


  • <table id="4yyaw"><kbd id="4yyaw"></kbd></table>
  • <td id="4yyaw"></td>
  • 调性视频