问题描述
有一个使用默认参数的类构造函数,或者我应该使用单独的重载构造函数吗?例如:
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.
这篇关于使用C ++构造函数的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!