成员数组包含类的实例。无法决定在哪里放置修改此类变量的方法
Map
类中有一个由 Block
组成的二维数组。我需要一个方法来更改类 Block
中的变量 value
。
class Block
{
Block(BlockValue blockValue = BLANK);
//first solution
void Block::setValue(BlockValue blockValue, Map &map);
void setImage(BlockValue blockValue, int n = 0);
//the value to be changed
BlockValue value;
static std::vector< std::vector<sf::Image> > images;
...
};
class Map
{
std::vector< std::vector<Block> > blocks;
//second solution
void setBlockValue(BlockValue blockValue, int i, int j);
...
};
我可以想到两种解决方案:
我在类
Block
中创建一个Block::setValue(BlockValue blockValue, Map &map)
并从Block 中调用它code>Map
的方式如下:blocks[i][j].setValue(blockValue, this);
我创建了一个
setBlockValue(BlockValue blockValue, int i, int j)
方法 int 类Map
。此解决方案的问题是我无法将构造函数用于Block
:Block::Block(BlockValue blockValue) { setValue(blockValue); }
您会推荐哪种解决方案
编辑:我忘记提及该方法有权访问 Block
数组非常重要。这就是为什么我在第一个方法的参数列表中包含 Map &map
的原因。我为这个可怕的错误道歉。
There is a two dimensional array of Block
s in the class Map
. I need a method to change the variable value
in the class Block
.
class Block
{
Block(BlockValue blockValue = BLANK);
//first solution
void Block::setValue(BlockValue blockValue, Map &map);
void setImage(BlockValue blockValue, int n = 0);
//the value to be changed
BlockValue value;
static std::vector< std::vector<sf::Image> > images;
...
};
class Map
{
std::vector< std::vector<Block> > blocks;
//second solution
void setBlockValue(BlockValue blockValue, int i, int j);
...
};
I can think of two solutions:
I create a
Block::setValue(BlockValue blockValue, Map &map)
in the classBlock
and call it from theMap
in the following way:blocks[i][j].setValue(blockValue, this);
I create a
setBlockValue(BlockValue blockValue, int i, int j)
method int the classMap
. The problem with this solution is that I can't use my constructor forBlock
:Block::Block(BlockValue blockValue) { setValue(blockValue); }
Which solution would you recommend?
EDIT: I forgot to mention that it is important that the method have access to the array of Block
s. That's why I included the Map &map
in the parameter list of the first method. I apologize for this terrible mistake.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的问题不太清楚,从清晰的角度来看,我会把两者结合起来。例如
,在
Map
中有一个方法可以为特定位置设置BlockValue
Your question is not very clear, from a clarity point of view, I'd combine both. e.g.
and in
Map
have a method to set theBlockValue
for a specific location您可以通过以下方式减少代码行数并提高效率:
返回引用将允许调用者使用赋值,
并且使您不必为读取和写入提供单独的调用。
You can reduce the number of lines of code and also improve efficiency with:
Returning a reference will allow the caller to use assignment
and will save you from having to provide separate calls for reading and writing.
我认为第一种解决方案更灵活。
如果 Block 会将其自身传递到映射,您可以在插入映射前或插入后时刻执行您想要的操作。
I think first solution more flexible.
If Block will past it self to map, your can do what you want on pre insert to map, or on post insert moments.