【发布时间】:2016-03-31 09:47:09
【问题描述】:
我有一个二维数组,我想定义一个函数,该函数返回用户使用运算符重载给我的索引值。 换句话说:
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,它迫使建立另一个运营商,我不想这样做。
数据矩阵定义如下
int** matrix; matrix = new int*[row];
if (matrix == NULL)
{
cout << "Allocation memory - Failed";
}
for (int i = 0; i < row; i++)//Allocation memory
{
matrix[i] = new int[col];
if (matrix[i] == NULL)
{
cout << "Allocation memory - Failed";
return;
}
}
我能做什么? 谢谢,
【问题讨论】:
-
简单地说,such an operator does not exist,所以你不能超载它。
-
好的,这意味着我必须为运算符 [] 构建两个函数,因为如果我这样做:
(((*this).matrix)[row])[col]那么第一个运算符将返回 int* 和第二个 int。跨度> -
@lilach 显示数据成员矩阵是如何定义的。
-
int** matrix; matrix = new int*[row]; if (matrix == NULL) { cout << "Allocation memory - Failed"; } for (int i = 0; i < row; i++)//Allocation memory { matrix[i] = new int[col]; if (matrix[i] == NULL) { cout << "Allocation memory - Failed"; return; } }
标签: c++ arrays operator-overloading 2d operator-keyword