运算符重载[] [] 2d数组c ++ [英] operator overloading [][] 2d array c++

查看:94
本文介绍了运算符重载[] [] 2d数组c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a 2D array and I want to define a function that returns the value of the index that the user gives me using operator overloading. In other words:

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,并且强制执行建立另一个运算符,我不想这么做.

The operation ((*this).matrix)[row][col] should return an int. I have no idea how to build the operator [][].
Alternatively, I could concatenate a couple of calls to the operator [], but I didn't succeed in it, because the first call to that operaror will return int* and the second one will return int, and it compel to build another operator, and I dont want to do that.

我该怎么办? 谢谢

推荐答案

简单来说,运算符不存在,因此您不能重载它.

Simply, such an operator does not exist, so you can not overload it.

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

A possible solution is to define two classes: the Matrix and the Row.
You can define the operator[] of a Matrix so that it returns a Row, then define the same operator for the Row so that it returns an actual value (int or whatever you want, your Matrix could be also a template).
This way, the statement myMatrix[row][col] will be legal and meaningful.

可以执行相同的操作,以便为Matrix分配新的Row或更改Row中的值.

The same can be done in order to assign a new Row to a Matrix or to change a value in a Row.

*编辑*

根据评论中的建议,您还应考虑 a>在这种情况下使用operator()而不是operator[].
这样,就不再需要Row类.

As suggested in the comments, also you should take in consideration to use operator() instead of operator[] for such a case.
This way, there wouldn't be anymore the need for a Row class too.

这篇关于运算符重载[] [] 2d数组c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆