如何声明具有默认参数的构造函数?

时间:2015-02-22 21:59:46

标签: c++ class constructor

如何编写可以接受默认参数的构造函数?声明私有数据成员或构造函数本身时,是否声明默认参数?

    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;
    }

我希望能够编写一个带默认参数的构造函数。但我不知道如何写一个(上面的表构造函数是我遇到问题的那个)。我想有一个具有不同重量,高度,宽度,长度的对象表,但所有表都是绿色的。 谢谢你的帮助!

1 个答案:

答案 0 :(得分:2)

使用成员初始化列表:

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参数。