【C++學習】顯式建構函式

來源:互聯網
上載者:User

作者:gnuhpc
出處:http://www.cnblogs.com/gnuhpc/

1.什麼是顯式建構函式?

首先要理解什麼是隱式建構函式,並且弄清它的優缺點。

#include <iostream>
using std::cout;
using std::endl;
class complexNumbers {
  double real, img;
public:
  complexNumbers() : real(0), img(0) { }
  complexNumbers(const complexNumbers& c) { real = c.real; img = c.img; }
  complexNumbers( double r, double i = 0.0) { real = r; img = i; }
  friend void display(complexNumbers cx);
};
void display(complexNumbers cx){
  cout<<"Real Part: "<<cx.real<<"Imag Part: "<<cx.img<<endl;
}
int main() {
  complexNumbers one(1);
  complexNumbers five = 5;
  display(one);
  display(five);
  return 0;
}

在這段代碼中,我們定義一個複數的模型,並且定義了三個建構函式,一個預設建構函式(第一個),一個複製建構函式(第二個),第三個就是協助我們實現隱式構造的建構函式。我們在主程式中使用了這個函數定義了兩個對象:

輸出為:

Real Part: 1 Imag Part: 0

Real Part: 5 Imag Part: 0

此時並沒有什麼問題,我們在主程式中加入一句話:display(300); 然後看結果,多列印了一行:

Real Part: 300 Imag Part: 0

這並非我們希望出現的結果,那這是如何發生的呢?

這裡display函數發現傳入的是一個數字300時,與它期待的類型(complexNumbers)不符合,它就隱式調用了建構函式進行對象的構造,產生一個臨時complexNumbers的執行個體對象。這種情況發生在存在可以接受一個參數的建構函式中(除複製建構函式)。

解決這個問題的方式就是強迫編譯器必須使用顯式構造的方式建立對象,這要在建構函式前使用explicit 關鍵字。回到這個例子,加上explicit後程式無法編譯,這樣就解決了該問題。如果還想方便使用的話只能如此顯式建立對象:

display(complexNumbers(200));

2.使用建議

在Google Style中,有明文要求在可以接受一個參數的建構函式(除複製建構函式)中必須使用explicit關鍵字防止這樣的情況。

作者:gnuhpc

出處:http://www.cnblogs.com/gnuhpc/

相關文章

聯繫我們

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