[英]Array subscript operator on a Matrix
我正在尝试在Matrix上重载Array下标运算符,但是我遇到了我无法理解的错误。 CMazeSquare &&运算符[](const tuple&other); 用于访问CMazeSquares矩阵的CMazeSquare网格**。 我希望能够通过说grid [someTuple]来访问CMazeSquare对象。
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[...]
。 它没有按照您的想法做。
最后,为什么要尝试返回右值引用? 您需要2个重载,一个重载用于const返回一个const左值引用,另一个重载用于mutable返回一个可变的引用。
我猜想的错误是因为您没有在C++11
进行编译,并且编译器无法理解&&
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.