c++ explicit的含義和用法

來源:互聯網
上載者:User

explicit用於修飾類的建構函式,表明該建構函式是顯式的,

 

用於使用者自訂類型的建構函式,制定它是預設的建構函式,不可用於轉換建構函式。因為建構函式有三種,1 拷貝建構函式 2 轉換建構函式 3 建構函式

當一個類存在多個建構函式時,explicit修飾的那個建構函式就是預設的。

class string{

private:

   int size;

   int capacity;

   char* buff;

public:

   string();

   string(int size);

   string(const char*);

   ~string();

};

 

int main(){

string s="Hello";

int ns=0;

s=1;

}

s=1,本來想ns=1,但是寫錯了,寫成了s=1,因為有個建構函式是接受一個int類型的參數,所以會試著用string(1)去

解釋它,為了避免類似的錯誤,我們會在前面加上explicit關鍵字,

explicit  string(int size)

 

一個很好的例子:

class People{

public:

   int age;

   explicit People(int a){

     age=a;

    }

};

void foo(void){

People p1(10);        //方式一

People* p_p2=new People(10);

People p3=10;         //方式三,這個會報錯,如果去掉explicit的話就不會報錯。

}

gcc -S people.cpp

聯繫我們

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