C++ 關鍵字explicit的使用情境

來源:互聯網
上載者:User

假若我們定義了Str類如下結構

class Str
{
  public:

    Str(int n)

    Str(const char* p)

  .....

}

可以使用如下方式來構建一個對象  

Str c(12);
Str d=Str(20);
Str *z=new Str(21);
Str a=10;//此處構建10個大小的空間
Str b="abcd";//此處構建特定字串大小空間
Str f='f';   //與設計不相符的構建方式,這裡會構建(int)'f'大小的記憶體空間

 

 

也許調用者是希望Str存'f'這一個字元,儘管Str沒有提供這樣的介面,但是編譯的時候並不會報錯,因為這裡存在隱式轉換,將char型轉換為Int型,這樣就與調用者的初衷不符合了。而使用explicit可以杜絕這種隱式轉換,在編譯的時候就不會讓其通過。可見explicit對於寫一些基礎庫供他人調用還是非常有必要的.

代碼:

#include<iostream>using namespace std;class Str{public:/*      explicit*/  Str(int n)//try explicit here        {                capacity=n;                getmem();        }        Str(const char* p)        {                capacity=strlen(p)+1;                getmem();                strcpy(strarr,p);        }        ~Str()        {                if(strarr!=NULL)                        free(strarr);        }        void printfvalue()        {                cout<<"len:"<<capacity<<"    str:"<<strarr<<endl;        }private:        void getmem()        {                strarr=(char*)malloc(sizeof(char)*capacity);        }private:        int  capacity;        char *strarr;};int main(){        Str c(12);        Str d=Str(20);        Str *z=new Str(21);        Str a=10;        Str b="abcd";        Str f='f';        c.printfvalue();        d.printfvalue();        z->printfvalue();        a.printfvalue();        b.printfvalue();        f.printfvalue();        return 1;}

  

相關文章

聯繫我們

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