【发布时间】:2017-04-05 07:27:13
【问题描述】:
所以我在 C++ 中遇到了一些问题(我的第一个编程语言是 C)。
假设我有以下课程:
2个标题(矩形和网格,假设点类很好,另一个假设是我们目前不需要打印函数)
Grid.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
{
/**/
}
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 函数并且构造函数没有完成)。
现在我要做的是,在 Grid.cpp 构造函数中,我正在尝试
动态分配数组的数组,但我只是无法理解 cpp 中类的内存分配背后的逻辑。
如果有人能向我解释 cpp 中的“新”功能如何在类和 n 维数组(类和一般情况下)上发挥作用,我将不胜感激。
希望你能理解我在这里遇到的问题。
提前致谢。
【问题讨论】:
-
不要在 c++ 中使用原始指针和
new/delete。请改用容器和智能指针。 -
关于:“假设是我们目前不需要打印功能”而不是做出假设,删除代码并证明它是正确的。您不仅会因为自己是对的而感到满足,而且您会拥有更小的寻找错误的表面积,并且更接近这个问题成为主题所需的minimal reproducible example。
-
不是完全重复,而是一个更好的方向:Initializing a two dimensional std::vector
标签: c++ class new-operator n-dimensional