这两个构造函数有什么区别?
这两个构造函数有什么区别?
int x, y; //position
BasePoint(int px, int py) : x(px), y(py) {}
以及
int x, y; //position
BasePoint(int px, int py)
{
x = px;
y = py;
}
x(px), y(py)
叫什么?什么时候使用这种类型的变量初始化?
谢谢。
What is the difference between this two constructor?
int x, y; //position
BasePoint(int px, int py) : x(px), y(py) {}
and
int x, y; //position
BasePoint(int px, int py)
{
x = px;
y = py;
}
What is x(px), y(py)
called? And When do I use this type of variable initialization?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第一个是使用
initialization-list
进行初始化,第二个是使用赋值运算符进行赋值。第一个推荐!
阅读此常见问题解答:我的构造函数是否应该使用“初始化列表”或“作业”?
常见问题解答的开头是:
阅读完整的答案。
First one is doing initialization using
initialization-list
, and second one is doing assignment using assignment operator.First one is recommended!
Read this FAQ : Should my constructors use "initialization lists" or "assignment"?
The FAQ answer starts with :
Read the complete answer.
x(px), y(py) 叫什么?
这些称为初始值设定项列表。您实际上所做的是将
px
的值复制到x
并将py
复制到y
。用途:
1. 请注意,派生构造函数的参数可以传递给基类构造函数。
2. 在这种情况下,编译器可以解析哪一个是参数,哪一个是成员变量。如果,这需要在构造函数中完成,那么 -
What is x(px), y(py) called?
These are called initializer lists. What you are actually doing is copying the value of
px
tox
andpy
toy
.Uses:
1. Notice that derived constructor's argument can be passed to base class constructor.
2. Compiler can resolve, in this case, which one is argument and which one is member variable. Had if, this needs to be done in the constructor,then -
这里你正在使用初始化列表
因此,构造时的对象不会进入主体并初始化这些值。它通过不进入构造函数的主体来节省时间。
另一个用途是在调用派生类构造函数时。
如果你使用这样的语句
,你可以这样写
here u are using the initialization list
so the object when constructed will not go inside the body and initiate those values.it saves time by not entering in the body of the constructor
Another use of this is when calling the derived class constructor.
where if you use the statement like
and you can write this