重载运算符[]
问题描述:
我重载了一个运算符[],但它没有按我的意愿工作。重载运算符[]
class A{
int *const e;
const int row, column;
public:
int rows() const
{
return row;
}
int columns() const
{
return column;
}
int size() const
{
return row * column;
}
A(int r, int c)
: row(r), column(c), e(new int[r*c])
{
for (int i = 0; i < r*c; i++)
{
e[i] = 0;
}
}
virtual int *const operator[ ](int r)
{
return &e[r*row];
}
}
例如: 如果我写道:
A a(2, 5)
a[0][0] = 1; // OK
a[0][1] = 2; // OK
a[0][2] = 3; // It's assigned a [0][2] == 3 but also [1][0] == 3
我没有发现问题。它应该为[0] [2]分配一个值3 这段代码有什么问题?
答
因为a[0][2]
和a[1][0]
是一个一样的。让我们看看:
&e[r*row]
与&(*(e+(r*row)))
(定义[]
)相同,与(e+(r*row))
相同。
如果r
为0,则这只是e
,并且如果r
为1,则这是(e+row)
。也就是说,假设您的row
为2,则为e+2
。
所以a[0]
返回e
和a[1]
返回e+2
。
现在a[0][2]
是(a[0])[2]
是e[2]
和a[1][0]
是(e+2)[0]
是e[2]
。看到?一样。
如果row
是行column
数列的数量,因为你的意图似乎是,你是最好返回&e[r*column]
您operator[]
(因为列数是一排的大小) 。
哦好吧,我已经改变了,但我仍然有同样的问题 – Cieja 2014-12-06 09:02:31
如果你改正了它,你不能有同样的问题。你可能有类似的问题,但不一样。 – 2014-12-06 09:14:07
是的,但我的意思是说结果是一样的 – Cieja 2014-12-06 10:46:32