如何简化 C++ 构造函数,将参数复制到其字段?

Gab*_*dez -2 c++ constructor simplify

这就是我所拥有的:

class Vector3 {
    private:
        float x;
        float y;
        float z;
    public:
        Vector3(float x = 0, float y = 0, float z = 0) {
            this->x = x;
            this->y = y;
            this->z = z;
        }
        ...
};
Run Code Online (Sandbox Code Playgroud)

我觉得this->something = something很重复。我只想用参数构造一次 Vector3 并

然后不再访问这些字段,只需使用方法添加 Vector3。

有什么方法可以简化构造函数而不需要这样做吗this->something = something?或者有什么方法可以“密封”这些字段?

小智 5

有什么方法可以简化构造函数,使其不必执行 this->something = Something 吗?

您可以使用成员初始值设定项列表来初始化数据成员:

class Vector3 {
    private:
        float x;
        float y;
        float z;
    public:
        Vector3(float x = 0, float y = 0, float z = 0): x(x), y(y), z(z) 
        {
        }
        ...
};
Run Code Online (Sandbox Code Playgroud)