构造函数可以预先赋一个初值,其作用是:在构造函数被调用时,省略部分或全部参数,这时就会使用默认参数代替实参。
程序:
#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;
}
运行结果:
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时,没有传入拷贝构造函数的实参,则形参w和h取默认值0
w = 0, h = 0
在构造函数中,weight = w = 0, height = h = 0
在area函数中, weight * height = 0
生成对象rec2时,传入实参5,相当于传入(5,0),则w = 5, h = 0
在构造函数中,weight = w = 5, height = h = 0
在area函数中,weight * height = 0
生成对象rec3时,传入实参(5,10),则w = 5, h = 10
在构造函数中, weight = w = 5, height = h = 10
在area函数中,weight * height = 50
加入少儿信息学奥赛学习QQ群请扫左侧二维码,关注微信公众号请扫右侧二维码
QQ群和公众号.png
网友评论