C++ 构造函数的默认参数

2021-12-30 00:00:00 constructor overloading coding-style c++

拥有一个使用默认参数的类构造函数是好习惯,还是应该使用单独的重载构造函数?例如:

//使用这个...类 foo{私人的:std::string name_;无符号整数年龄_;上市:foo(const std::string& name = "", const unsigned int age = 0) :名称_(名称),年龄_(年龄){...}};//或这个?类 foo{私人的:std::string name_;无符号整数年龄_;上市:富():名称_(""),年龄_(0){}foo(const std::string& name, const unsigned int age) :名称_(名称),年龄_(年龄){...}};

任一版本似乎都有效,例如:

foo f1;foo f2("姓名", 30);

您更喜欢或推荐哪种风格,为什么?

解决方案

绝对是风格问题.我更喜欢带有默认参数的构造函数,只要参数有意义.标准中的类也使用它们,这对他们有利.

需要注意的一件事是,如果除了一个参数之外的所有参数都有默认值,则您的类可以从该参数类型隐式转换.查看此主题了解更多信息.>

Is it good practice to have a class constructor that uses default parameters, or should I use separate overloaded constructors? For example:

// Use this...
class foo  
{
private:
    std::string name_;
    unsigned int age_;
public:
    foo(const std::string& name = "", const unsigned int age = 0) :
        name_(name),
        age_(age)
    {
        ...
    }
};

// Or this?
class foo  
{
private:
    std::string name_;
    unsigned int age_;
public:
    foo() :
    name_(""),
    age_(0)
{
}

foo(const std::string& name, const unsigned int age) :
        name_(name),
        age_(age)
    {
        ...
    }
};

Either version seems to work, e.g.:

foo f1;
foo f2("Name", 30);

Which style do you prefer or recommend and why?

解决方案

Definitely a matter of style. I prefer constructors with default parameters, so long as the parameters make sense. Classes in the standard use them as well, which speaks in their favor.

One thing to watch out for is if you have defaults for all but one parameter, your class can be implicitly converted from that parameter type. Check out this thread for more info.

相关文章