实现中的构造函数与标头

Nic*_*age 5 c++ implementation header

据我所知,构造函数应该在实现文件中定义,但我只能在一个主文件中找到包含类的示例,而不是拆分为 .h 和 .cpp 文件

我需要知道的是我的以下代码是否以可接受的方式分开。

实体.h:

    using namespace std;

class cEntity {
private:
    /*-----------------------------
    ----------Init Methods---------
    -----------------------------*/
    int *X, *Y;
    int *Height, *Width;

public:
    /*-----------------------------
    ----------Constructor----------
    -----------------------------*/
    cEntity (int,int, int, int);

    /*-----------------------------
    ----------Destructor-----------
    -----------------------------*/
    ~cEntity ();

    /*-----------------------------
    ----------Set Methods----------
    -----------------------------*/

    /*Set X,Y Methods*/
    void setX(int x){*X=x;};
    void setY(int y){*Y=y;};
    void setXY(int x, int y){*X=x; *Y=y;};

    /*Set Height, Width Methods*/
    void setHeight(int x){*Height=x;};
    void setWidth(int x){*Width=x;};
    void setDimensions(int x, int y){*Height=x; *Width=y;};

    /*-----------------------------
    ----------Get Methods----------
    -----------------------------*/

    /*Get X,Y Methods*/
    int getX(){return *X;};
    int getY(){return *Y;};

    /*Get Height, Width Methods*/
    int getHeight(){return *Height;};
    int getWidth(){return *Width;};
};
Run Code Online (Sandbox Code Playgroud)

和实体.cpp:

#include "Entity.h"


cEntity::cEntity (int x, int y, int height, int width) {
   X,Y,Height,Width = new int;
  *X = x;
  *Y = y;
  *Height = height;
  *Width = width;
}

cEntity::~cEntity () {
  delete X, Y, Height, Width;
}
Run Code Online (Sandbox Code Playgroud)

我还要感谢大家的帮助,尤其是在我的第一个问题上!

Moo*_*uck 5

cEntity::cEntity (int x, int y, int height, int width) {
Run Code Online (Sandbox Code Playgroud)

是正确的

   X,Y,Height,Width = new int;
Run Code Online (Sandbox Code Playgroud)

没那么多。这设置Width为一个新的int,但不是其余的。您可能打算:

   X = new int(x);
   Y = new int(y);
   Height = new int(height);
   Width = new int(width);
Run Code Online (Sandbox Code Playgroud)

请注意,这种构造方法不适用于没有赋值/复制的对象,例如引用。对于某些对象,它也比就地构建它们慢。因此,首选的构建方式如下:

cEntity::cEntity (int x, int y, int height, int width) {
    :X(new int(x))
    ,Y(new int(y))
    ,Height(new int(height))
    ,Width(new int(width))
{}
Run Code Online (Sandbox Code Playgroud)

这更好,但如果抛出任何异常,您将不得不以某种方式释放已分配的异常。更好的方法是让每个成员都成为std::unique_ptr<int>,这样他们就会自行解除分配并为您省去很多麻烦。

  • 或者根本不给他们指点。那么它们的分配就在对象本身内部,并且当 cEntity 对象被销毁时它们将被释放。 (2认同)