对象构造函数的C ++ 2D数组
在我的Dev C ++中,我试图创建一个像Grid一样的2D Array类。
但是问题之一是我不确定该对构造函数做什么。
In my Dev C++, I am trying to create a 2D Array class that acts like a Grid. But one of the problem is I am unsure what do for the constructor.
当我尝试编译时,出现以下错误:
在构造函数'Grid :: Grid(int,int)'中:
'sqaures'不是类型
'yPos'不能出现在常量表达式
中[Build Error] [grid。 o]错误1
When I try to compile, I get the following errors: In constructor 'Grid::Grid(int,int)': 'sqaures' is not a type 'yPos' cannot appear in a constant-expression [Build Error] [grid.o] Error 1
以下是头文件:
#ifndef GRID_H
#define GRID_H
using namespace std;
class Grid
{
public:
Grid(int xPos, int yPos);
// Constructor
// POST: Creates the squares of grid; (x,y) coordinates
private:
int squares;
//2D Array
//the squares; (x,y) coordinates of the grids
};
#endif
这是网格功能的.cpp文件.h
And heres the .cpp file for the functions of grid.h
#include <iostream>
#include "grid.h"
using namespace std;
Grid::Grid(int xPos, int yPos)
{
squares = new squares[xPos][yPos];
//Trying to make squares into a 2D array, and turn the values into the arguments
//into the the x,y coordinates
}
.cpp文件中的构造函数不起作用,我不确定该怎么做。有人有任何解决方案吗?
My constructor in the .cpp files doesn't work and I'm unsure what to do. Does anyone have any solutions?
您的代码有一些问题。
首先,您的成员变量 squares应为指向int的指针,而不是 int :
There are a few problems with your code. First of all, your member variable "squares" should be a pointer to an int, not an int:
int *squares;
然后,以下行将出现错误:
Then, the following line will give an error:
squares = new squares[xPos][yPos];
您真正需要的是2D数组的内存块:
What you really need is a block of memory for the 2D array:
squares = new squares[xPos * yPos];
此外,您还应将此数组的尺寸保存在成员变量中(例如 sizeX和 sizeY)
Also, you should save the dimensions of this array in member variables (e.g., "sizeX" and "sizeY" )
现在,您有一块内存,可以容纳2D正方形数组。我通常会重载()运算符以访问此数组中的元素:
Now, you have a block of memory which will hold a 2D array of squares. I usually overload the () operator for accessing an element in this array:
int &Grid::operator() (int x, int y)
{
// you can check array boundaries here
return squares[y + sizeX*x];
}
如果您对运算符有疑问,只需创建一个成员函数即可:
If you have problems with the operator stuff, just create a member function instead:
int Grid::get(int x, int y)
{
// check array bounds
return squares[y + sizeX*x];
}
void Grid::set(int x, int y, int value)
{
// check array bounds
squares[y + sizeX*x] = value;
}
最后,您需要一个析构函数来释放内存:
Finally, you need a destructor to free the memory:
Grid::~Grid()
{
delete [] squares;
}
这就是我喜欢这样做的方式( C类 )。在另一个答案中,David Norman提供了一种很好的标准C ++方式来实现您的类。
This is how I like to do it (the "C-with-classes" style). In another answer, David Norman gives a good "Standard C++" way of implementing your class.