본문 바로가기
C++/열혈 C++

열혈 C++ 객체를 저장하는 배열 클래스 // []연산자 오버로딩

by Beijing_KingGod 2018. 4. 9.

#include <iostream>
using namespace std;

class Point{
private:
 int x,y;
public:
 Point(int _x=0, int _y=0):x(_x), y(_y){}
 friend ostream& operator<<(ostream& os, const Point& p);
};

ostream& operator<<(ostream& os, const Point& p)
{
 os<<"["<<p.x<<","<<p.y<<"]";
 return os;
}

/*****************PointArr Class****************/
const int SIZE=5; //저장소의 크기

class PointArr{
private:
 Point arr[SIZE];
 int idx;
public:
 PointArr():idx(0){}
 void AddElem(const Point& elem);
 void ShowAllData();
 Point& operator[](int i); //배열 요소에 접근
};

void PointArr::AddElem(const Point& elem){
 if(idx>=SIZE){
  cout<<"용량 초과!"<<endl;
  return;
 }
 arr[idx++]=elem;
}
void PointArr::ShowAllData(){
 for(int i=0; i<idx; i++)
  cout<<" arr["<<i<<"]="<<arr[i]<<endl;// 여기서 연산자 오버로딩 실행
        //멤버 함수Point& PointArr::operator[](int i) 실행
       //전역함수 ostream& operator<<(ostream& os, const Point& p) 실행
}

Point& PointArr::operator[](int i){
 return arr[i];
}

int main(void)
{
 PointArr arr;
 
 arr.AddElem(Point(1,1)); //[PointArr]arr.arr[0] = 임시객체 // 생성되자마자 바로 배열에 복사후 소멸
 arr.AddElem(Point(2,2)); //[PointArr]arr.arr[1]
 arr.AddElem(Point(3,3)); //[PointArr]arr.arr[2]
 arr.ShowAllData();

 // 개별 요소 접근 및 변경//Point& PointArr::operator[](int i) 실행
 arr[0]=Point(10,10);  // [PointArr] arr.arr[0] = Point(10,10)
 arr[1]=Point(20,20);
 arr[2]=Point(30,30);

 cout<<arr[0]<<endl;
 cout<<arr[1]<<endl;
 cout<<arr[2]<<endl;

 return 0;
}

댓글