3 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個贊
使用轉(zhuǎn)換構(gòu)造函數(shù)隱式轉(zhuǎn)換
讓我們在問題中做出更復(fù)雜的例子
class MyClass{ public: int a, b; MyClass( int i ) {} MyClass( const char* n, int k = 0 ) {} MyClass( MyClass& obj ) {}}
前兩個構(gòu)造函數(shù)正在轉(zhuǎn)換構(gòu)造函數(shù)。第三個是復(fù)制構(gòu)造函數(shù),因此它是另一個轉(zhuǎn)換構(gòu)造函數(shù)。
轉(zhuǎn)換構(gòu)造函數(shù)允許從參數(shù)類型到構(gòu)造函數(shù)類型的隱式轉(zhuǎn)換。這里,第一個構(gòu)造函數(shù)允許從一個int
類轉(zhuǎn)換為一個對象MyClass
。第二個構(gòu)造函數(shù)允許從字符串轉(zhuǎn)換為類的對象MyClass
。第三......從班級MyClass
的對象到班級的對象MyClass
!
要成為轉(zhuǎn)換構(gòu)造函數(shù),構(gòu)造函數(shù)必須具有單個參數(shù)(在第二個參數(shù)中,第二個參數(shù)具有一個默認(rèn)值)并且不使用關(guān)鍵字進(jìn)行聲明explicit
。
然后,main中的初始化可能如下所示:
int main(){ MyClass M = 1 ; // which is an alternative to MyClass M = MyClass(1) ; MyClass M = "super" ; // which is an alternative to MyClass M = MyClass("super", 0) ; // or MyClass M = MyClass("super") ;}
顯式關(guān)鍵字和構(gòu)造函數(shù)
現(xiàn)在,如果我們使用了explicit
關(guān)鍵字怎么辦?
class MyClass{ public: int a, b; explicit MyClass( int i ) {}}
然后,編譯器不會接受
int main() { MyClass M = 1 ; }
因?yàn)檫@是隱式轉(zhuǎn)換。相反,必須寫
int main() { MyClass M(1) ; MyClass M = MyClass(1) ; MyClass* M = new MyClass(1) ; MyClass M = (MyClass)1; MyClass M = static_cast<MyClass>(1); }
explicit
始終使用關(guān)鍵字來防止構(gòu)造函數(shù)的隱式轉(zhuǎn)換,它適用于類聲明中的構(gòu)造函數(shù)。

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個贊
轉(zhuǎn)換構(gòu)造函數(shù)是單參數(shù)構(gòu)造函數(shù),聲明時沒有顯式的函數(shù)說明符。編譯器使用轉(zhuǎn)換構(gòu)造函數(shù)將對象從第一個參數(shù)的類型轉(zhuǎn)換為轉(zhuǎn)換構(gòu)造函數(shù)類的類型。
- 3 回答
- 0 關(guān)注
- 451 瀏覽
添加回答
舉報