【问题标题】:Array subscript operator on a Matrix矩阵上的数组下标运算符
【发布时间】:2016-10-29 17:41:46
【问题描述】:

我正在尝试在 Matrix 上重载 Array 下标运算符,但是我遇到了一个我无法理解的错误。 CMazeSquare && operator[] (const tuple &other);旨在访问 CMazeSquare 网格**,它是 CMazeSquares 的矩阵。我希望能够通过说 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];
}

【问题讨论】:

  • && 不是逻辑与运算符的意思吗?
  • @H.Jabi 没有。这里它是类型的一部分,表示引用
  • addWalls 和其他类似问题的一部分吗?请减少您的代码minimal reproducible example
  • @bolov 我一直认为引用是用一个&amp; 声明的。与 c++ 的长期距离,对我自己很不利:(
  • @bolov 谢谢,已更改。

标签: c++ multidimensional-array


【解决方案1】:

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 中编译并且编译器不理解&amp;&amp;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    相关资源
    最近更新 更多