Two dimensional array in C++ / Compiler / Overload

2019-09-17 20:09发布

Actually I have a question about two dimensional arrays in C++. The first question is how the Compiler interprets the two dimensional array with difference to a "normal" one dimensional array. Then I need to implement a operator overload for two dimensional arrays.

This is the overloaded operator for normal array:

const float& Matrix::operator[] (int index) const
{
    const float& value = this->m[index];
    return value;
}

This is the overloaded operator for two dimensional array:

const float& Matrix::operator[][](int index, int ndIndex) const
{
    const float& value = this->m[index][ndIndex];
    return value;
}

Is this the theorethical correct implementation for a [][] operator overload?

Then there is a question why it's difficult to get write access to the array in the [][] solution. The last question is that this problem can be solved with a Proxy pattern, but I never heard Proxy as a programm pattern.

All these questions are theoretical so I dont need real code, just the context "behind the scene" and a scetch about the proxy pattern.

Would nice if you could help me out! Thanks in advance!!

2条回答
SAY GOODBYE
2楼-- · 2019-09-17 20:17

There is no operator[][] in C++. You don't need a fancy proxy, just overload operator[] and make it return an array (which corresponds to the row). In a sense, this is the proxy (the array you return)

Something like:

float* Matrix::operator[](int row) // non-const version
{
    return m[row];
}

and

const float* Matrix::operator[](int row) const // const overload
{
    return m[row];
}
查看更多
疯言疯语
3楼-- · 2019-09-17 20:32

(Next time please ask 2 questions if you have 2 questions. SO is free.)

To clarify the second part of the question, a Proxy object is an object that stands for a row of the 2D array. It's returned by the first level operator[], and the Proxy itself implements the second operator[].

查看更多
登录 后发表回答