矩阵上的数组下标操作符



我试图在矩阵上重载数组下标操作符,但是我得到了一个我无法理解的错误。cmazessquare &&Operator [] (const tuple &other);表示访问CMazeSquare网格**,它是CMazeSquares的矩阵。我希望能够通过输入grid[someTuple]

来访问cmazessquare对象
CMaze.h:61:17: error: expected unqualified-id before ‘&&’ token
     CMazeSquare && operator [] (const tuple &other);
                 ^

我怎么也弄不明白这里出了什么问题。请帮助。

#ifndef CMAZE_H
#define CMAZE_H
struct tuple
{
    short x;
    short y;
    tuple();
    tuple(const tuple &other);
    tuple(short X, short Y);
    tuple operator + (const tuple &other);
};
class CMaze
{
    public:
    private:
    struct CMazeSquare
    {
        CMazeSquare ();
        void Display (ostream & outs);
        sType what;
        bool vistited;

    };
    CMazeSquare ** grid;
    CMazeSquare && operator [] (const tuple &other); //<- This is the problem
};
#endif

我认为操作符的实现应该是这样的:

//in CMaze.cpp
CMaze::CMazeSquare && CMaze::operator [](tuple &other)
{
    return this[other.x][other.y];
}

operator[]通常是这样重载的:

CMazeSquare& operator[] (const tuple &other)
{
   return grid[other.x][other.y];
}
const CMazeSquare& operator[] const (const tuple &other)
{
   return grid[other.x][other.y];
}

你的代码有几个问题:

首先,定义与声明不匹配:

CMazeSquare && operator [] (const tuple &other);
vs
CMaze::CMazeSquare && CMaze::operator [](tuple &other)

注意定义参数中缺少const

那么你不能说this[...]。它并不像你想象的那样。

最后,为什么你试图返回一个右值引用?你需要两个重载,一个用于const返回const左值引用,另一个用于mutable返回可变引用。


你得到的错误我想是因为你不编译在C++11和编译器不理解&&

相关内容

  • 没有找到相关文章