본문 바로가기

PROGRAMMING LANGUAGE/C++

[]연산자 오버로딩

#include <iostream>
#include <algorithm>
using namespace std;

class CIntArray
{
private:
	int* m_pnData;
	int m_nSize;
public:
	CIntArray(int nSize)
	{
		m_pnData = new int[nSize];
		memset(m_pnData, 0, sizeof(int) * nSize);
	}
	~CIntArray() { delete m_pnData; }

	int Get(int index)
	{
		
		return m_pnData[index];
	}

	void Set(int index, int value)
	{
		m_pnData[index] = value;
	}

	int& operator[](int index)
	{
		return m_pnData[index];
	}    

};

int main()
{
	CIntArray arr(5);

	for (size_t i = 0; i < 5; i++)
	{
		arr[i] = i + 1;
	}

	cout << arr[1] << endl;

	arr.Set(0, 10);
	arr.Set(1, 20);
	cout << arr.Get(0) << endl;
	cout << arr.Get(1) << endl;
	return 0;
}