如何声明具有默认参数的构造函数
How to declare a constructor that has default parameter?
如何编写一个可以接受默认参数的构造函数?在声明私有数据成员时还是在构造函数内部声明默认参数?
Color class:
private:
int red;
int blue;
int green;
public:
Color(int r, int b, int g) {red = r; blue = b; green = g;}
Table class:
private:
double weight;
double height;
double width;
double length;
Color green;
public:
Table(double input_weight, double input_height, double input_width,
double input_length, Color green = green(0, 0, 60)){
weight = input_weight;
height = input_height;
width = input_width;
length = input_length;
}
我希望能够编写一个采用默认参数的构造函数。但我不知道如何编写一个(上面的表构造函数是我遇到问题的那个)。我想要一个有不同重量、高度、宽度和长度的对象表,但所有的表都是绿色的。谢谢你的帮助!
使用成员初始化列表:
public:
Table(double input_weight, double input_height, double input_width, double input_length)
: weight(input_weight)
, height(input_height)
, width(input_width)
, length(input_length)
, green(Color(0, 0, 60))
{
}
正如其他人所指出的,您的原始代码中有一个拼写错误,应该使用Color(0,0,60)来调用构造函数。
如果你真的想保留你的表构造函数签名,你可以这样做:
public:
Table(double input_weight, double input_height, double input_width, double input_length, Color default_color=Color(0, 0, 60))
: weight(input_weight)
, height(input_height)
, width(input_width)
, length(input_length)
, green(default_color)
{
}
基本上,为构造函数定义默认参数遵循与任何函数的默认参数相同的规则。但是,如果您真的需要Color参数,那么您应该只在构造函数中有它。
相关文章:
- 如何使用默认参数等选择模板专业化
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 何时提供默认参数作为模板参数
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 如何修复带有 clang 的参数'args'缺少默认参数的问题?
- 函数不接受 X 参数,函数使用默认参数
- initializer_list具有默认参数的构造函数
- C++ 带有默认参数的结构,可选择在构造函数中更改
- 为什么C++构造函数在继承中需要默认参数?
- 必须非常量别名参数及其默认参数常量
- C++ 默认参数使用其他参数
- 组合函数参数包和默认参数
- 如何定义 Vector2f 的默认参数?[SFML]
- 有条件地将默认参数传递给函数(使用"?"运算符)
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- 如何设置默认参数以防用户不输入另一个参数
- 结构 c++ 中的默认参数
- 构造函数委托与默认参数
- 默认参数和函数指针作为函数参数C++
- 如何在继承层次结构中调用具有默认参数的构造函数?