Using the Subscript Operator in Programming a Dynamic Array
#include <iostream>
using namespace std;
class CMyArray
{
private:
int* m_pnInternalArray;
int m_nNumElements;
public:
CMyArray (int nNumElements);
~CMyArray ();
// a subscript operator
int& operator [] (int nIndex);
};
int& CMyArray::operator [] (int nIndex)
{
return m_pnInternalArray [nIndex];
}
CMyArray::CMyArray (int nNumElements)
{
m_pnInternalArray = new int [nNumElements];
m_nNumElements = nNumElements;
}
CMyArray::~CMyArray ()
{
delete [] m_pnInternalArray;
}
int main ()
{
CMyArray mArray (5);
mArray [0] = 25;
mArray [1] = 20;
mArray [2] = 15;
mArray [3] = 10;
mArray [4] = 5;
for (int nIndex = 0; nIndex < 5; ++ nIndex)
std::cout << mArray [nIndex] << " ";
return 0;
}
Related examples in the same category