C++的隱式類型轉換

來源:互聯網
上載者:User

標籤:

C++是一種複雜的語言,其中有許多“好玩”的特性,學習C++的過程就像在海邊撿一顆顆石頭,只要堅持不懈,也許一顆顆小石頭也能建起你自己小小的城堡。

廢話完後,講講自己撿到的石頭:隱式類型轉換 

學習出處:《Effective C++》 lostmouse大人翻譯

 


class TestInt
{

public:
    int GetData()const{ return i;};
    TestInt(int ii):i(ii){}; //建構函式

private:
    int i;

};

void fun(TestInt t)

{
    cout<<t.GetData()<<endl;
}

int main()

{

    fun(10);

    return 0;

}

運行結果:

10

為啥fun函數需要的是TestInt的類型的參數,而傳進去int 也可以呢,

尋找原因之前,我們先把建構函式注釋掉,再重新編譯,結果這次直接報錯error: conversion from ‘int’ to non-scalar type ‘TestInt

好像有點眉目了,之前能夠調用成功估計和類的這個建構函式有關,其實這就是C++中的隱式類型轉換:

編譯器知道傳個fun的值是int而函數需要的是TestInt,但他也同時知道調用TestInt的建構函式將int轉換成一個合適的TestInt,

我們知道函數傳值是會產生一個臨時變數,現在的情況就類似 const TestInt t(10),所以結果就如上面所示。

 

《Effective C++》中一個例子:

class Month {
public:
  static const Month Jan() { return 1; }
  static const Month Feb() { return 2; }
  ...
  static const Month Dec() { return 12; }

  int asInt() const           // 為了方便,使Month
  { return monthNumber; }     // 可以被轉換為int

private:
  Month(int number): monthNumber(number) {}

  const int monthNumber;
};

一開始不明白如何調用這個類,而且對 static const Month Jan() { return 1; }

這個函數的傳回值有很大的疑問,為啥傳回型別是Month,但函數能返回一個int呢。

想不通,只好敲進編譯器試錯,經過一次次的出錯,終於弄清這個類的用法,

其實這個類就是想得到一個const的月份:Month jan = Month::Jan(); 這樣就得到代表一月份的對象。

而 static const Month Jan() { return 1; } 能夠成功就是利用了隱式類型轉換,只是現在的建構函式是

私人的,為的是防止使用者建立新的month。

 

“只通過看遊泳的書,並不能讓你真正學會遊泳”,編程也是如此。

 

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.