构造函数中冒号后的变量

2021-12-30 00:00:00 constructor c++ ctor-initializer

我仍在学习 C++ 并试图理解它.我正在查看一些代码并看到:

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
{
}

构造函数参数旁边的x(X), y(Y), z(Z)"是什么意思?

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

推荐答案

这是一种调用 point3 类成员的构造函数的方法.如果 x、y 和 z 是浮点数,那么这只是一种更有效的写法

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;
}

但是如果 x, y &z 是类,那么这是将参数传递给它们的构造函数的唯一方法

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

相关文章