explicit
class A{public: A(); //default構(gòu)造函數(shù)};class C{public: explicit C(int x); //不是default構(gòu)造函數(shù)};構(gòu)造函數(shù)被聲明為explicit,這可阻止它們被用來執(zhí)行隱式類型轉(zhuǎn)換,但它們?nèi)钥杀挥脕磉M(jìn)行顯式類型轉(zhuǎn)換:
void doSomething(C cObject);C cObj1;doSomething(cObj1); //okC cObj2(28);doSomething(28); //WRONG 該函數(shù)接受一個C,而不是int,而int和C之間沒有隱式轉(zhuǎn)換doSomething(C(28)); //OK,使用C構(gòu)造函數(shù)將int顯式轉(zhuǎn)換被聲明為explicit的構(gòu)造函數(shù)通常比其non-explicit更受歡迎,因為它們禁止編譯器執(zhí)行非預(yù)期的類型轉(zhuǎn)換。
copy構(gòu)造函數(shù)
copy構(gòu)造函數(shù)被用來“以同型對象初始化自我對象”,copy assignment操作符被用來“從另一同型對象中拷貝其值到自我對象”
class Widget{public: Widget(); //default構(gòu)造函數(shù) Widget(const Widget& rhs); //copy構(gòu)造函數(shù) Widget& Operator=(const Widget& rhs); //copy assignment操作符 ...};Widget W1; //調(diào)用default構(gòu)造函數(shù)Widget W2(W1); //調(diào)用copy構(gòu)造函數(shù)W1=W2; //調(diào)用copy assignment操作符Widget W3=W2; //賦值符號“=”也可用來調(diào)用copy構(gòu)造函數(shù)copy構(gòu)造函數(shù)是一個尤其重要的函數(shù),因為它定義一個對象如何passed by value(以值傳遞)
bool hasAcceptableQuality(Widget w);...Widget aWidget;if(hasAcceptableQuality(aWidget)){ ...}參數(shù)w是以by value方式傳遞給hasAcceptableQuality,所以在上述調(diào)用中aWidget被復(fù)制到w體。這個復(fù)制動作是由Widget的copy構(gòu)造函數(shù)完成。passed by value意味著調(diào)用copy構(gòu)造函數(shù)。
以by value傳遞用戶自定義類型通常是bad idea,pass by reference to const往往是比較好的選擇
新聞熱點
疑難解答
圖片精選