C++构造函数默认值设置

C++构造函数默认值设置

构造函数默认值

C++类中构造函数设置默认值应当注意:

  1. C++类构造函数只能对排在最后的参数提供默认值;
  2. 既可以在构造函数的声明中,也可以在构造函数的实现中,提供缺省值,但,不能在两者同时提供缺省默认值。

代码

#include <iostream>

using namespace std;

class CTest
{
public:    
    CTest();
    CTest(int _a, double _b, const bool _c = false, bool _d = true);

private:
    const bool c;
    bool d;
    int a;
    double b; 
};

CTest::CTest(int _a, double _b = 1.0, const bool _c,  bool _d):a(_a), b(_b), c(_c), d(_d)
{
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
    cout << d << endl;  
}

int main()
{
    // CTest* test = new CTest(1, 1.0, true, false);
    // CTest* test = new CTest(1, 1.0, true);
    //CTest* test = new CTest(1, 1.0);
    CTest* test = new CTest(1);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值