实现中的构造函数与标头

新手上路,请多包涵

据我所知,构造函数应该在实现文件中定义,但我只能在一个主文件中找到类的示例,而不是拆分为 .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;};
};

和Entity.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;
}

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

原文由 Nick Savage 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 317
2 个回答
cEntity::cEntity (int x, int y, int height, int width) {

是正确的

   X,Y,Height,Width = new int;

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

    X = new int(x);
   Y = new int(y);
   Height = new int(height);
   Width = new int(width);

请注意,这种构造方法不适用于没有分配/复制的对象,例如引用。对于某些对象,它也比在适当位置构建它们要慢。因此,优选的构造方式如下:

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

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

原文由 Mooing Duck 发布,翻译遵循 CC BY-SA 3.0 许可协议

好的,可以。但是,您的构造函数和析构函数存在问题。您的代码实际上所做的是分配一个 int,而您的析构函数也释放一个 int。无论如何,这里没有必要使用指针。更好的实现(如果我们不使用智能指针)可能是:

[实体.h]

 private:
    /*Private fields*/
    int X, Y;
    int Height, Width;

[实体.cpp]

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

还有一件事情。尽量避免在头文件中出现 using namespace std; 。如果你这样做,你会强制那些包含你的标题的人使用这个 using 语句,它可能会引发命名空间冲突。

原文由 Marek Kurdej 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题