小朋友學(xué)C++(9):構(gòu)造函數(shù)的默認參數(shù)

構(gòu)造函數(shù)可以預(yù)先賦一個初值,其作用是:在構(gòu)造函數(shù)被調(diào)用時,省略部分或全部參數(shù),這時就會使用默認參數(shù)代替實參。

程序:

#include <iostream>
using namespace std;

class Rectangle
{
private:
    int width;
    int height; 
public:
    Rectangle(int w = 0, int h = 0)
    {
        cout << "Constructor method is invoked!" << endl;
        width = w;
        height = h;
    }
    
    int area()
    {
        return width * height; 
    }
};

int main(int argc, char** argv) 
{
    Rectangle rec1;
    cout << "Area of rec1 is : " << rec1.area() << endl;
    
    Rectangle rec2(5);
    cout << "Area of rec2 is : " << rec2.area() << endl;
    
    Rectangle rec3(5, 10);
    cout << "Area of rec3 is : " << rec3.area() << endl;
    
    return 0;   
}

運行結(jié)果:

Constructor method is invoked!
Area of rec1 is : 0
Constructor method is invoked!
Area of rec2 is : 0
Constructor method is invoked!
Area of rec3 is : 50

分析:
生成對象rec1時,沒有傳入拷貝構(gòu)造函數(shù)的實參,則形參w和h取默認值0
w = 0, h = 0
在構(gòu)造函數(shù)中,weight = w = 0, height = h = 0
在area函數(shù)中, weight * height = 0

生成對象rec2時,傳入實參5,相當于傳入(5,0),則w = 5, h = 0
在構(gòu)造函數(shù)中,weight = w = 5, height = h = 0
在area函數(shù)中,weight * height = 0

生成對象rec3時,傳入實參(5,10),則w = 5, h = 10
在構(gòu)造函數(shù)中, weight = w = 5, height = h = 10
在area函數(shù)中,weight * height = 50


加入少兒信息學(xué)奧賽學(xué)習(xí)QQ群請掃左側(cè)二維碼,關(guān)注微信公眾號請掃右側(cè)二維碼


QQ群和公眾號.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容