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++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16