Default parameters with C++ constructors(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.
这篇关于C++ 构造函数的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 构造函数的默认参数


- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 近似搜索的工作原理 2021-01-01
- 从python回调到c++的选项 2022-11-16
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01