If I remove const from the copy constructor MyArray(const MyArray& cArrayInput), all is well. Otherwise the following compile error occurs at the line m_paArray[i] = cArrayInput[i]:
error C2678: binary ‘[‘ : no operator found which takes a left-hand operand of type ‘const MyArray’ (or there is no acceptable conversion).
I know I can use cArrayInput.m_paArray[i]. But how to use the overloaded subscript function?
class MyArray
{
private:
int m_nLength;
double* m_paArray;
public:
MyArray():m_nLength(0),m_paArray(0)
{
}
// copy constructor
MyArray(const MyArray& cArrayInput)
{
m_nLength = cArrayInput.m_nLength;
m_paArray = new double[m_nLength];
for(int i=0;i<m_nLength;i++)
m_paArray[i] = cArrayInput[i];
}
double& operator[](const int nIndex)
{
assert(nIndex >= 0 && nIndex < m_nLength);
return m_paArray[nIndex];
}
};
The problem is that you are calling a non-const operator on a
constinstance ofMyArray. So you need to provide aconstversion ofoperator[]:Note that you can provide this version in addition to the non-const version.
As an aside, it may be an idea to to something other than call
assertif the index is out of bounds. You could an throw an exception, for example. That gives the caller code the opportunity to at least recover and do something. The std::out_of_range exception is designed for these cases.