运算符重载[] [] 2d数组c ++

问题描述 投票:5回答:2

我有一个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;
}

((*this).matrix)[row][col]操作应返回int。我不知道如何构建operator [][]。另外,我可以将几个对operator []的调用串联起来,但是我没有成功,因为对该操作员的第一个调用将返回int*,第二个调用将返回int,并且强制执行建立另一个运算符,我不想这样做。

我该怎么办?谢谢,

c++ arrays operator-overloading 2d operator-keyword
2个回答
6
投票

简单来说,such an operator does not exist,所以不能使它过载。

一种可能的解决方案是定义两个类:MatrixRow。您可以定义operator[]Matrix以使其返回Row,然后为Row定义相同的运算符,以使其返回实际值(int或您想要的任何值,即[C0 ]也可以是模板)。这样,语句Matrix将是合法且有意义的。

为了将新的myMatrix[row][col]分配给Row或更改Matrix中的值,可以进行相同的操作。

*编辑*

如注释中所建议,在这种情况下,您也应该Row使用take in consideration而不是operator()。这样,就不再需要operator[]类。


3
投票

您可以为课程定义自己的Row。一种简单的方法可以如下所示

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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.