如何声明具有默认参数的构造函数?
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;
}
我希望能够编写一个带有默认参数的构造函数。但我不知道如何写一个(上面的 Table 构造函数是我遇到问题的那个)。我想要一个具有不同重量、高度、宽度、长度的对象 Table,但所有表格都是绿色的。
感谢您的帮助!
使用成员初始化列表:
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) 来调用构造函数。
如果你真的想保留你的 Table 构造函数签名,你可以这样做:
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 参数。
如何编写可以接受默认参数的构造函数?我是在声明私有数据成员时还是在构造函数本身内部声明默认参数?
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;
}
我希望能够编写一个带有默认参数的构造函数。但我不知道如何写一个(上面的 Table 构造函数是我遇到问题的那个)。我想要一个具有不同重量、高度、宽度、长度的对象 Table,但所有表格都是绿色的。 感谢您的帮助!
使用成员初始化列表:
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) 来调用构造函数。
如果你真的想保留你的 Table 构造函数签名,你可以这样做:
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 参数。