构造函数默认值
C++类中构造函数设置默认值应当注意:
- C++类构造函数只能对排在最后的参数提供默认值;
- 既可以在构造函数的声明中,也可以在构造函数的实现中,提供缺省值,但,不能在两者同时提供缺省默认值。
代码
#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;
}