operator overloading [] [] 2d array c ++

LIM*_*IMA 5 c++ arrays 2d operator-overloading operator-keyword

我有一个2D数组,我想定义一个函数,它返回用户使用运算符重载的索引值.换一种说法:

void MyMatrix::ReturnValue()
{
    int row = 0, col = 0;
    cout << "Return Value From the last Matrix" << endl;
    cout << "----------------------------------" << endl;
    cout << "Please Enter the index: [" << row << "][" << col << "] =" << ((*this).matrix)[row][col] << endl;
}
Run Code Online (Sandbox Code Playgroud)

该操作((*this).matrix)[row][col]应该返回一个int.我不知道如何建立operator [][].
或者,我可以连接几个调用operator [],但我没有成功,因为第一次调用该操作将返回int*,第二次将返回int,它强制构建另一个运算符,我不想去做.

我能做什么?谢谢,

sky*_*ack 6

简单地说,这样的操作符不存在,因此您不能超载它.

一种可能的解决方案是定义两个类:MatrixRow.
您可以定义operator[]a,Matrix以便它返回a Row,然后定义相同的运算符,Row以便它返回实际值(int或者您想要的任何值,您Matrix也可以是模板).
这样,该陈述myMatrix[row][col]将是合法且有意义的.

同样可以为了分配新做RowMatrix或改变一个值Row.

*编辑*

正如评论中所建议的那样,您也应该考虑使用operator()而不是operator[]针对这种情况.
这样,就不再需要Row课程了.


Vla*_*cow 6

您可以operator []为类定义自己的。一个简单的方法可以看下面的方式

#include <iostream>
#include <iomanip>

struct A
{
    enum { Rows = 3, Cols = 4 };
    int matrix[Rows][Cols];
    int ( & operator []( size_t i ) )[Cols]
    {
        return matrix[i];
    }
};

int main()
{
    A a;

    for ( size_t i = 0; i < a.Rows; i++ )
    {
        for ( size_t j = 0; j < a.Cols; j++ ) a[i][j] = a.Cols * i + j;
    }


    for ( size_t i = 0; i < a.Rows; i++ )
    {
        for ( size_t j = 0; j < a.Cols; j++ ) std::cout << std::setw( 2 ) << a[i][j] << ' ';
        std::cout << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

程序输出是

 0  1  2  3 
 4  5  6  7 
 8  9 10 11 
Run Code Online (Sandbox Code Playgroud)

  • 它之所以有效,是因为它返回对数组所选行的引用,然后可以使用“[]”进一步索引该行 - 该类型是“int &amp; [Cols]”,这是“matrix[i]”的真实结果类型` 在它衰变为指针之前。然而,在相同的成员函数指针联盟中,返回此类引用的函数的语法是丑陋且令人困惑的,因此大多数人不会理会它,而只是返回指向相关行的第一个元素的指针。 (2认同)
  • 尽管我很欣赏这里和那里的良好 WAT,但我是否可以建议使用尾随返回类型 (2认同)
  • @lilach为了使定义更简单,您可以为返回类型引入 using 别名或类型 def 。例如 struct A { enum { Rows = 3, Cols = 4 }; 使用 TRow = int ( &amp; )[Cols]; int 矩阵[行][列]; TRow 运算符 []( size_t i ) { 返回矩阵[i]; } }; (2认同)