前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >小朋友学C++(9):构造函数的默认参数

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

作者头像
海天一树
发布2018-04-17 12:11:45
1K0
发布2018-04-17 12:11:45
举报
文章被收录于专栏:海天一树海天一树

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

程序:

代码语言:javascript
复制
#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;   
}

运行结果:

代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-12-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 海天一树 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档