C++自動類型轉化--特殊建構函式方法和重載的運算子方法

來源:互聯網
上載者:User

標籤:amp   exp   logs   ace   names   編譯   輸出   void   xpl   

一、重載運算子法

#include <stdio.h>#include <iostream>class Three{    int i;public:    Three(int ii = 0, int = 0) : i(ii)     {        std::cout << "you call Three()" << std::endl;    }};class Four{    int x;public:    Four(int xx) : x(xx) {}    operator Three() const { return Three(x);}};void g(Three) {}int main(){    Four four(1);    g(four);    g(1);//calls Three(1,0)    int n;    std::cin >> n;}
//輸出兩次:
you call Three()

2.建構函式轉換

//這個建構函式能夠把另一類型的對象(引用)作為它的單個參數,那麼建構函式允許編譯器執行自動類型轉換;
#include <stdio.h>#include <iostream>class One{public: One() {} };class Two{public: Two(const One&) { std::cout << "you call Two()" << std::endl; }};void f(Two) {}int main(){ One one; f(one);//wants a Two ,has a one
//輸出:"you call Two()”
    int i;    std::cin >> i;}
注意:以上方法調用了Two的隱藏的建構函式,如果關心調用效率的話不要這樣使用!

3.阻止建構函式被隱式調用,要求必須顯示調用:

//使用關鍵詞explicit時,必須顯示調用,完成類型轉換
#include <stdio.h>#include <iostream>using namespace std;class One{public: One() { }};class Two{public: explicit Two(const One&) {}};void f(Two) {}int main(){ One one; //!f(one);//NO auto conversion allowed f(Two(one)); //int i; //cin >> i;}

 

C++自動類型轉化--特殊建構函式方法和重載的運算子方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.