据我所知,构造函数应该在实现文件中定义,但我只能在一个主文件中找到类的示例,而不是拆分为 .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 许可协议
是正确的
没那么多。这将
Width
设置为新的int
,但不是其余的。您可能打算:请注意,这种构造方法不适用于没有分配/复制的对象,例如引用。对于某些对象,它也比在适当位置构建它们要慢。因此,优选的构造方式如下:
这更好,但如果抛出任何异常,您将不得不以某种方式解除分配已分配的异常。更好的是让每个成员都成为
std::unique_ptr<int>
,这样他们就会释放自己并为您省去很多麻烦。