所以我在 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
矩形.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:
矩形.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
{
/**/
}
网格.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 函数并且构造函数没有完成)。
现在我要做的是,在 Grid.cpp 构造函数中,我试图动态分配数组数组,但我无法理解 cpp 中类的内存分配背后的逻辑。如果有人可以向我解释 cpp 中的“新”功能如何在类和 n 维数组(类和一般情况下)上发挥作用,我将不胜感激。
我希望你能理解我在这里遇到的问题。
提前致谢。