小朋友学C++(9):构造函数的默认参数

网友投稿 880 2022-09-04

小朋友学C++(9):构造函数的默认参数

小朋友学C++(9):构造函数的默认参数

构造函数可以预先赋一个初值,其作用是:在构造函数被调用时,省略部分或全部参数,这时就会使用默认参数代替实参。

程序:

#include 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 0Constructor method is invoked!Area of rec2 is 0Constructor 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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:深入理解php的输出缓冲区(output buffer)
下一篇:小朋友学C++(11):“箭头(->)”和“点号(.)”操作符的区别
相关文章

 发表评论

暂时没有评论,来抢沙发吧~