explicit建構函式和非explicit建構函式

來源:互聯網
上載者:User
代碼 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Base{
 5 public:
 6     explicit Base(int i=0):ival(i)
 7     {
 8         cout << "Class Base's constructure is called" << endl;
 9     }
10     Base(const Base& b)
11     {
12         cout << "Class Base's copy constructure is called" << endl;
13     }
14 private:
15     int ival;
16 };
17 
18 class Base1{
19 public:
20     Base1(int ival): mybase(ival)
21     {
22         cout << "Base1's constructure is called" << endl;
23     }
24 private:
25     Base mybase;
26 };
27 
28 void fun(Base b)
29 {
30     cout << "fun is OK" << endl;
31 }
32 
33 void main()
34 {
35     int val = 5;
36     Base1 base1(val);
37     cout << endl;
38     fun(Base(val));
39 
40     int ival;
41     cin >> ival;
42 }

 

Base1的建構函式的成員初始化列表中,調用的是explicit的建構函式,注意不是copy建構函式。

如果Base的建構函式不聲明為explicit,若想以int類型實參調用fun函數,則fun的形參必須為Base對象,為Base&則錯誤。

如果Base的建構函式為explicit,不可用int形參調用fun(Base b)。 

聯繫我們

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