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++ 构造函数的默认参数
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
