假若我們定義了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;}