Variables after the colon in a constructor [duplicate]

ぐ巨炮叔叔 提交于 2019-11-27 03:46:52

问题


I am still learning C++ and trying to understand it. I was looking through some code and saw:

point3(float X, float Y, float Z) :
x(X), y(Y), z(Z)  // <----- what is this used for
{
}

What is the meaning of the "x(X), y(Y), z(Z)" sitting beside the constructor's parameters?


回答1:


It's a way of invoking the constructors of members of the point3 class. if x,y, and z are floats, then this is just a more efficient way of writing this

point3( float X, float Y, float Z):
{
   x = X;
   y = Y;
   z = Z;
}

But if x, y & z are classes, then this is the only way to pass parameters into their constructors




回答2:


In your example point3 is the constructor of the class with the same name (point3), and the stuff to the right of the colon : before the opening bracket { is the initialization list, which in turn constructs (i.e. initializes) point3's member variables (and can also be used to pass arguments to constructors in the base class[es], if any.)




回答3:


Member initialization as others have pointed out. But it is more important to know the following:

When the arguments are of the type float or other built-in types, there's no clear advantages except that using member initialization rather than assignment (in the body of the constructor) is more idiomatic in C++.

The clear advantage is if the arguments are of user-defined classes, this member initialization would result in calls to copy constructors as opposed to default constructors if done using assignments (in the constructor's body).



来源:https://stackoverflow.com/questions/2349978/variables-after-the-colon-in-a-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!