尝试将Ruby自定义数组访问器转换为C ++下标运算符覆盖

问题描述 投票:-2回答:1

我正在学习如何使用“Mazes for Programmers:Code your Own Twisty Little Passages”这本书来创建迷宫。这些例子都在Ruby中。我目前正在学习高级C ++,我想转换这段代码。

def [](row, column)
  return nil unless row.between?(0, @rows - 1)
  return nil unless column.between?(0, @grid[row].count - 1)
@grid[row][column] end

#Buck, Jamis. Mazes for Programmers: Code Your Own Twisty Little Passages
#(p. 21). Pragmatic Bookshelf. Kindle Edition.

上面的代码从给定行和列的网格返回一个Cell对象,如果这样的Cell存在的话。我已经研究过在C ++中覆盖[]运算符,但Ruby实现使用了一个二维数组。我完全迷失了如何实现它以检查行和列。


这是Grid Class的标题:

#include "Cell.h"

class Grid
{
private:
    int rows;
    int columns;
    vector<vector<Cell>> grid;
public:
    Grid(int, int);
    ~Grid();
    void prepareGrid();
    void configureCells();
    Cell &operator[] (int,int);
};

我希望能够做到这样的事情:

Cell & Grid::operator[](int row, int column)
{
    if (row >= rows) {
        return NULL;
    }
    else if (column >= columns) {
        return NULL;
    }
    else {
        return grid[row][column];
    }
}

  • 编辑以澄清

:C ++运算符[]不允许多个参数,因此我无法使用访问者的单个覆盖检查行和列

我也意识到返回NULL在这种情况下是无效的,需要弄清楚如何解决这个问题。

c++ ruby
1个回答
0
投票

我完全迷失了如何实现它以检查行和列。

像这样使用and&&

if (row < rows && column < columns)
{
    // success
}
else
{
    // fail
}

为了指示失败,您可以更改函数签名以返回Cell*,这将允许您返回nullptr(不要使用NULL)或者您可以抛出异常。

© www.soinside.com 2019 - 2024. All rights reserved.