第42課 - 類型轉換函式(下)__函數

來源:互聯網
上載者:User

1、問題

        類類型是否能夠類型轉換到普通類型。


2、類型轉換函式

        C++類中可以定義類型轉換函式 

        類型轉換函式用於將類對象轉換為其它類型 

        文法規則:

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


3、編程實驗

 類型轉換函式初探     42-1.cpp

#include <iostream>   #include <string>      using namespace std;      class Test   {       int mValue;   public:       Test(int i = 0)       {           mValue = i;       }       int value()       {           return mValue;       }       operator int ()       {           return mValue;       }   };      int main()   {          Test t(100);       int i = t;  //t.operator int()            cout << "t.value() = " << t.value() << endl;       cout << "i = " << i << endl;              return 0;   }  


                


        類型轉換函式 

            -與轉換建構函式具有同等的地位 

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

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


        編譯器會儘力嘗試讓源碼通過編譯  Test t(1);       int i= t;   


        t這個對象為Test類型,怎麼可能用於初始化int類型的變數呢。

        現在就報錯嗎。 不急,我看看有沒有類型轉換函式! Ok, 發現

        Test類中定義了operator int () , 可以進行轉換。



        類類型之間的相互轉換。。                 類型轉換函式vs轉換建構函式 


4、編程實驗

類類型之間的轉換     42-2.cpp

#include <iostream>   #include <string>      using namespace std;      class Test;      class Value   {   public:       Value()       {       }       Value(Test& t)       {       }   };      class Test   {       

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.