2016-11-21 152 views
-1

所以我在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中的'新'功能。

我希望你能理解我在這裏遇到的問題。

在此先感謝。

+1

不要在C++中使用原始指針和'new' /'delete'。改用容器和智能指針。 –

+0

關於:「假設是我們目前不需要打印功能」而不是做出假設,刪除代碼並證明它是正確的。你不僅會滿足於正確的觀點,而且你將有一個更小的搜尋表面積,並且更接近這個問題所要求的[mcve]。 – user4581301

+0

不完全重複,但更好的方向去:[初始化二維std ::向量](http://stackoverflow.com/questions/17663186/initializing-a-two-維度 - 向量) – user4581301

回答

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維地址一樣。關於在CS13中關於keren calif的新面貌的問題。 NODELMAN是國王!

+0

是的,但如果我們正在討論的是n維數組,你將無法跟蹤索引,所以我寧願找到一個解決方案,如何將它分解爲數組數組(如果有的話)。 –

+0

我不確定沒有默認構造函數就可能 – benz