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

How to declare a constructor that has default parameter?

本文关键字:默认 参数 构造函数 何声明 声明      更新时间:2023-10-16

如何编写一个可以接受默认参数的构造函数?在声明私有数据成员时还是在构造函数内部声明默认参数?

    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参数,那么您应该只在构造函数中有它。