所以我在C++中遇到了一些问题(我的第一个编程语言是C)。类的C++矩阵(指针指针)
比方说,我有以下类别:
2头(矩形和电网,假设点类是细而另一个假设是,我们并不需要目前打印功能)
电网。^h
#ifndef GRID_H
#define GRID_H
#ifndef RECT_H
#include "Rectangle.h"
#endif
class Grid
{
public:
Grid(int tileW, int tileH, int width, int height, int color);
~Grid();
Rectangle& getRectAt(const Point &p);
void print() const;
private:
int count;
Rectangle **recs;
};
#endif
Rect.h
#ifndef RECT_H
#define RECT_H
#ifndef POINT_H
#include "Point.h"
#endif
class Rectangle
{
public:
Rectangle(int l, int u, int w, int h, int color);
int getColor() const;
void setColor(int color);
bool contains(const Point &p) const;
void print() const;
private:
const Point topLeft, bottomRight;
int color;
};
#endif
和2 CPP的:
Rect.cpp
#include "Rectangle.h"
Rectangle::Rectangle(int l, int u, int w, int h, int color) : topLeft(l, u), bottomRight(l + w, u + h) { this->color = color; }
int Rectangle::getColor() const
{
return this->color;
}
void Rectangle::setColor(int color)
{
this->color = color;
}
bool Rectangle::contains(const Point &p) const
{
return (this->topLeft.getX < p.getX && p.getX < this->bottomRight.getX
&& this->bottomRight.getY < p.getY && p.getY < this->bottomRight.getY);
}
void Rectangle::print() const
{
/**/
}
Grid.cpp
#include "Grid.h"
Grid::Grid(int tileW, int tileH, int width, int height, int color)
{
int index, index_c=0;
recs = new Rectangle *[width];
for (int index = 0; index < width; index++)
{
recs[index] = new Rectangle [height];
}
}
(假设我们不需要其他的网格功能,构造函数没有完成)。
现在我想要做的是这个,在Grid.cpp的构造函数中,我试图 动态分配数组的数组,但我只是不明白cpp中类的内存分配背后的逻辑。 我将不胜感激,如果有人能解释我是如何在类和n维数组(类和一般)上的cpp中的'新'功能。
我希望你能理解我在这里遇到的问题。
在此先感谢。
不要在C++中使用原始指针和'new' /'delete'。改用容器和智能指针。 –
关于:“假设是我们目前不需要打印功能”而不是做出假设,删除代码并证明它是正确的。你不仅会满足于正确的观点,而且你将有一个更小的搜寻表面积,并且更接近这个问题所要求的[mcve]。 – user4581301
不完全重复,但更好的方向去:[初始化二维std ::向量](http://stackoverflow.com/questions/17663186/initializing-a-two-维度 - 向量) – user4581301