第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

什么是C ++中的轉(zhuǎn)換構(gòu)造函數(shù)?它是為了什么?

什么是C ++中的轉(zhuǎn)換構(gòu)造函數(shù)?它是為了什么?

C++
慕標(biāo)琳琳 2019-08-19 10:16:04
什么是C ++中的轉(zhuǎn)換構(gòu)造函數(shù)?它是為了什么?我聽說C ++有一些叫做“轉(zhuǎn)換構(gòu)造函數(shù)”或“轉(zhuǎn)換構(gòu)造函數(shù)”的東西。這些是什么,它們的用途是什么?我在這段代碼中看到了它:class MyClass{   public:      int a, b;      MyClass( int i ) {}}  int main(){     MyClass M = 1 ;}
查看完整描述

3 回答

?
慕勒3428872

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ù)。


查看完整回答
反對 回復(fù) 2019-08-19
?
幕布斯7119047

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ù)類的類型。


查看完整回答
反對 回復(fù) 2019-08-19
  • 3 回答
  • 0 關(guān)注
  • 451 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號