【发布时间】:2014-12-23 02:31:36
【问题描述】:
所以我一直在为二维数组类重载运算符()。对于我正在做的随机测试,return 设置为array[0][index]。现在只传递列设置为 0 的索引(行)。如果索引小于行(那么我们在下一行),它仍然返回数据,就像我指定了列一样?
基本代码示例:
class myArr
{
private:
float array[3][3];
public:
myArr::myArr(float a1, float a2, ... ) { array[0][0] = a1; array[0][1] = a2; ... }
// ^ the "..." just means, the same action till float a9/array[2][2] = a9;
float& operator() (unsigned index) { return array[0][index]; }
const float operator() (unsigned index) const { return array[0][index]; }
};
int main()
{
myArr test(1, 2, 3, 4, 5, 6, 7, 8, 9);
std::cout << myArr(4) << std::endl; // Displays 5
myArr(4) = 0; // Set's element 4 to hold value 0
return 0;
}
奇怪的是,这行得通。我可以使用 1 个参数设置/获取第 5 个元素。现在我想知道它为什么/如何工作,当然它应该出错“超出范围”或其他东西。最后,这会是“安全的”还是您强烈建议不要这样做?
我很少使用二维数组,主要是因为它们缺乏性能提升。
【问题讨论】:
标签: c++ class operator-overloading multidimensional-array