C++ : 연산자 오버로딩(8) - 객체의 저장을 위한 배열 클래스

참고 : 열혈강의 C++ 프로그래밍 책
#include <iostream>
#include <cstdlib>

using namespace std;

class APoint
{
private:
 int x, y;

public:
 APoint(int px = 0, int py = 0) : x(px), y(py) { }
 friend ostream& operator<<(ostream& os, const APoint& pos);
};

ostream& operator<<(ostream& os, const APoint& pos)
{
 os <<  '[' << pos.x << ", " << pos.y << ']' << endl;

 return os;
}

// 객체의 주소값을 저장하기 위한 용도
typedef APoint* POINT_PTR;

class APointArray
{
private:
 POINT_PTR* arr;
 int arrlen;

 APointArray(const APointArray& arr) { }
 APointArray& operator=(const APointArray& arr) { }

public:
 APointArray(int len) : arrlen(len)
 {
  arr = new POINT_PTR[len];
 }

 POINT_PTR& operator[] (int idx)
 {
  if(idx < 0 || idx >= arrlen)
  {
   cout << "Array index out of bound exception" << endl;
   exit(1);
  }

  return arr[idx];
 }

 POINT_PTR& operator[] (int idx) const
 {
  if(idx < 0 || idx >= arrlen)
  {
   cout << "Array index out of bound exception" << endl;
   exit(1);
  }

  return arr[idx];
 }

 int GetArrlen() const { return arrlen; }

 ~APointArray() { delete []arr; }
};

// 테스트
void Operator8()
{
 // 객체의 주소를 저장하면 얕은 복사와 깊은 복사를 신경쓰지 않아도 된다.
 APointArray arr(3);
 arr[0] = new APoint(3, 4);
 arr[1] = new APoint(5, 6);
 arr[2] = new APoint(7, 8);

 for(int i = 0; i < arr.GetArrlen(); i++)
  cout << *(arr[i]);
 
 for(int i = 0; i < arr.GetArrlen(); i++)
  delete arr[i];
}

댓글

이 블로그의 인기 게시물

C++ : Class로 만든 DLL Export 및 Import

VMware 환경에서 우분투로 안드로이드 환경 구축하기(1)