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++ 构造函数的默认参数


基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07