关于c++中构造函数的问题
我是c++新手,我还没有见过这种构造函数,它是做什么的?
class A {
int x;
public:
A(int xx):x(xx) {}
};
int main() {
A a(10);
A b(5);
return 0;
}
上面的代码有效吗?
这个构造函数是做什么的? A(int xx):x(xx) 是什么意思?演员阵容?
I am newbie to c++, I have not yet seen this kind of constructor, what does it do?
class A {
int x;
public:
A(int xx):x(xx) {}
};
int main() {
A a(10);
A b(5);
return 0;
}
Is the code above valid?
What does this constructor do? A(int xx):x(xx) means what? A cast?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
是的。
它被称为初始化列表,它将
xx
复制到类成员x
。Yes.
It is called initializer list which copies
xx
to the class memberx
.:
之后和正文之前(空大括号)的内容是一个初始化列表。它用xx
初始化成员变量x
。请参阅 C++ 常见问题解答中的此部分:http://www.parashift .com/c++-faq-lite/ctors.html#faq-10.6。
The stuff after the
:
and before the body (the empty braces) is an initializer list. It initializes the member variablex
withxx
.See this section from the C++ FAQ: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6.
字符串
:x(xx)
称为初始值设定项。正如您所看到的,它仅对构造函数有效。效果是用值 xx 初始化 x。因此,您的代码创建了两个 A 对象 - 一个的 x 为 10,另一个的 x 为 5。这比让它初始化然后通过编写
x=xx;< 在构造函数主体中更改其值更有效。 /代码>
The string
:x(xx)
is called an initializer. As you can see it's valid on only a constructor. The effect is to initialize x with the value xx. So your code makes two A objects - one has an x of 10 and the other of 5.This is more efficient than letting it be initialized and then changing its value in the body of the constructor by writing
x=xx;
这称为初始化列表。当调用构造函数时,私有变量 x 将被初始化为 xx。
That is called an initialization list. The private variable x will be initialized with xx when the constructor is called.
这是一个带有初始化器的构造函数。
x(xx)
使用xx
的值初始化 xThat's a constructor with an initializer.
The
x(xx)
initializes x with the value ofxx
A(int xx) : x(xx)
使用xx
的值初始化数据成员x
。A(int xx) : x(xx)
initializes the data memberx
with the value ofxx
.代码有效:成员变量“
x
”正在“基/成员初始值设定项列表”中设置值。当您初始化引用成员、常量成员的值或将参数转发到基本构造函数时,需要这种类型的初始化。
在其他情况下,它是可选的,例如本例,该值可以在构造函数主体中显式设置(但这可以说更快,因为它是在分配内存时初始化的)。
The code is valid: The member variable "
x
" is being set a value in the "base/member initializer list".This type of initialization is required when you are initializing a value for a reference member, constant member, or to forward arguments to the base constructor.
It is optional in other cases, like this one, where the value could have been explicitly set in the constructor body (but this is arguably faster, since it is initialized as memory is allocated).