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];
}
};