在另一个类中使用类的操作

时间:2015-10-22 09:36:37

标签: c++ function class

我有一个私人成员的迷宫课程:

int i,j; // Position in an array bidimensional i rows, j columns in map
int x,y; // Position to draw the class in opengl, x coord and y coord in screen

所以我需要从i(地图,数组)转换为y(屏幕)和j转换为x。 内部类迷宫ID也有如下操作:

int maze::getTransformMaptoScreenY(int i); would return the y value "translated" to screen size of the position i in the array
the same to j and get the x value in the screen

int maze::getTransformScreentoMapY(int i);
would return the i value "translated" from screen to map (array)
the same to j and get the Y value in the screen

所以我需要在迷宫操作draw中使用这些操作,比如

void Maze::draw()
{
 //ive to tranlate the walls, food, corridor from map to screen
 for i in rows
   for j in columns
         translate i,j to screen X,Y ( use getTransformMaptoScreenY and getTransformMaptoScreenX )
}

所以我需要一个公共函数getTransformMaptoScreenY,也许还需要一个私有函数来执行相同的操作和代码。

不知道它是否是更好的实现方式,或者我是否可以从一个函数调用getTransformMaptoScreenY ....

2 个答案:

答案 0 :(得分:1)

  

所以我需要一个公共函数getTransformMaptoScreenY和   也许是一个私有函数,可以执行相同的操作和代码。

听起来像是 NVI -idiom的完美候选人:

https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface

答案 1 :(得分:0)

我建议您不要向Maze类添加显示方法,而是创建一个知道屏幕以及如何将迷宫坐标转换为屏幕坐标的MazeDisplayer类。将迷宫视为模型,MazeDisplayer提供该模型的视图。在我谈论模型和视图时,请查看https://en.wikipedia.org/wiki/Model-view-80-controller了解我所指的内容。

您可以通过在其中注入迷宫和屏幕来构建MazeDisplayer,例如

class MazeDisplayer {
public :
  MazeDisplayer(const Maze& maze, Screen& screen);
  ...
}