Class 'Friend' Useage

In the code below, I'm trying to consolidate the "private" members of these two classes. CELL is a part of grid. When a grid is created, it creates a bunch of cells.. (Think Excel for visual example)

Both CELL and grid will have functions that require access to these four starting variables for various calculations: cellHeight, cellWidth, gridRows, gridColumns - which are initialized in the grid.Create() function.

Is there a way I can structure my code so that I only have to declare, initialize, and access these variables from ONE source? Otherwise, I have to copy all the variables into every single CELL that's created within the grid to function properly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class CELL{
public:
  int Height();
  int Width();
  rectangle Rectangle();
  point Point();
  point PointCenter();
  point PointBottomRight();	
  int Neighbor(Direction dir);
  int Row();
  int Column();
  int MoveCost;
private:
  int z_cellHeight;
  int z_cellWidth;
  int z_gridRows;
  int z_gridColumns;
};

class grid{
// friend class CELL; ????
public:
  std::vector<CELL> Cell;
  void Create(int Rows, int Columns, int CellHeight, int CellWidth);
private:
  int z_cellHeight;
  int z_cellWidth;
  int z_gridRows;
  int z_gridColumns;
};

int main()
{
  //Example usage
  grid g;
  g.Create(5,5,32,32);
  int x = g.Cell[2].Row();  //Returns the row this cell is on
}
Think of what makes logical sense. Firstly, why does 'CELL' need to know how many rows / columns there are? This should all be handled by 'grid'. Also, I assume that the height/width of the cell is dependent on the overall height/width of the row/column, so you should probably move that over to 'grid' as well. Basically. eveything related to the grid should be owned by 'grid', and only the things related to the cell itself (namely, its individual data or whatever) should be owned by 'CELL'.
Point() is a function that returns the upper left corner X and Y values of a given cell. In order to calculate this, I have to know where a cell is located in relation to the rest of the grid. Here is how I would calculate this...



1
2
3
4
5
6
7
8
9
10
11
12
13
// Example passed as g.Cell[Index].Point();

point Point()
{
   point nPoint(0,0);
  //Solve for X
  nPoint.X = Index;
  if (nPoint.X >= z_gridRows) nPoint.X = nPoint.X % z_gridRows;
  nPoint.X *= z_cellWidth;
  //Solve for Y
  nPoint.Y = (Index / z_gridRows) * z_cellHeight;
  return nPoint;
}


This is just one example of why I need to access those variables in the CELL class.
Last edited on
Topic archived. No new replies allowed.