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

本文介绍构造函数如何使用默认参数,并通过实例演示不同情况下构造函数如何为成员变量赋值。展示了当省略实参时,默认参数的使用效果。

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

程序:

#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



更多内容请关注微信公众号
wechat.jpg

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值