正在用 new 初始化一个 cpp class

Initalizing a cpp class with new

我创建了一个 Vector3 class:

 class Vector3{

   public:
   float x, y, z;
};

我能做到:

Vector3 v;
v.x = 0.0f;
v.y = 0.0f;
v.z = 0.0f

我想这样初始化:

Vector3 v = new Vector3(0.0f, 0.0f, 0.0f);

我想你是在问如何编写初始化成员的构造函数:

class Vector3{
    public:
    float x, y, z;
    Vector3(float a,float b, float c) : x(a),y(b),z(c) {}
    Vector3() : x(0.0f), y(0.0f), z(0.0f) {}
};

现在你可以写了

Vector3 v(0.0f, 0.0f, 0.0f);
Vector3 v2;

不要使用new创建对象。如果你真的需要一个动态分配的对象,那么使用智能指针。