0

そのため、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

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 関数は必要なく、コンストラクターが完成していないと仮定します)。
今私がやろうとしているのはこれです.Grid.cppコンストラクターで、配列の配列を動的に割り当てようとしていますが、cppのクラスのメモリ割り当ての背後にあるロジックを理解できません. クラスおよびn次元配列(クラスおよび一般的な)でcppの「新しい」機能がどのように機能するかを誰かが説明してくれれば幸いです。

ここで遭遇する問題を理解していただければ幸いです。

前もって感謝します。

4

2 に答える 2

0
Grid::Grid(int tileW, int tileH, int width, int height, int color)  // האם ניתן להניח את תקינות הקלט ? 
{
  int i ,j ; 
  i=0;
  count=height*width;
  recs=new Rectangle* [count];
 
  for(i=0;i<count;i++)
   for(j=0;j<width;j++)
    {
        recs[i+j]=new Rectangle (tileW*j,tileH*i,tileW,1,tileH);
    }

}

1 つの長い配列を使用し、2 次元のようにアドレス指定する必要があります。

于 2016-11-21T20:28:18.460 に答える