構(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
