C++.5 iostream & "<< , >>" operator overriding

lsw·2021년 4월 4일
0

C++

목록 보기
5/8
post-thumbnail

1. 개요

iostream파일의 표준함수인 "cout <<" , "cin >>" 모두 연산자 오버로딩에 의한 약속된 규칙임을 알아보고 객체의 "<< , >>"연산을 위한 오버라이딩을 시도해보자.


2. 요약설명

  • 연산자 '<<' 의 오버라이딩 함수를 멤버로 지닌 "ostream" 클래스와 연산자 '>>'의 오버라이딩 함수를 멤버로 지닌 "istream" 클래스를 담고있는 헤더파일 iostream.
  • iostream 헤더파일 내 std라는 namespace 하에 "cin"은 iostream형 객체로, "cout"은 ostream형 객체로 정의돼 있다. 따라서..
  1. #include
  2. using namespace std;
  3. cin >> , cout << (해당 클래스 내 연산자 오버라이딩)

3. 코드

	#include <iostream>

두개의 class(istream, ostream)와 namespace std를 포함한 헤더파일 iostream 참조

using namespace std;

std 이름공간 내 각 istream, ostream 클래스 객체로 정의된 cout, cin에 자유로이 접근하기 위해 "using namespace std;" 선언

class Point
{
  private:
  int xpos, ypos;

  public:
  Point(int x=0, int y=0)
  : xpos(x), ypos(y)
  {
  }

/*
1. **ostream 참조형**으로 반환해야 꼬리를 무는식으로(cout << 5 << "+"  << 7 << "=" ....)
  표현 가능
2. "<<"기능함수(기존 오버라이딩)에 접근할 수 있는 본객체는 ostream class type 이기에
    Point class의 멤버 내 오버라이딩이 불가능(인자로 ostream &, 연산을 원하는 classtype &)
*/
  friend ostream & operator<<(ostream & ost, Point & pos);
// ostream 참조형 반환, 
// 동일
  friend istream & operator>>(istream & ist, Point & pos);
};

/*
 문자, int등은 이미 ostream에서 << 연산자 오버로딩이 되어 있으나 내가 원하는 특정 
객체를 피연산자로 하는 << 연산자 오버로딩은 되어있지 않기에 이를 생성하기 위한 전역 오버로딩
*/
ostream & operator<<(ostream & ost, Point & pos)
{
  ost << "[xpos : " << pos.xpos << ", ypos : " << pos.ypos << "]" << endl;
  return ost;
}

// << 연산자와 동일
istream & operator>>(istream & ist, Point & pos)
{
  ist >> pos.xpos >> pos.ypos;
  return ist;
}

자세한 설명은 상기 코드 참조

int main()
{
  Point pos1;
// std -> cout(ostream object), std -> cin(istream object)
  cout << "x와 y값을 입력하시오 : "; cin >> pos1 ; 
// Point class object인 pos1을 피연산자로 연산 진행
  cout << pos1;
  Point pos2;
  cout << "x와 y값을 입력하시오 : "; cin >> pos2;
  cout << pos2;
  return 0;
}

4. 결과


5. 결론

<< , >>의 피연산자로 문자, 스트링, 정수, 실수 an so on...뿐 아니라 객체(object)가 올 수 있도록 멤버 외 연산자 오버로딩이 가능하다. 또한 std::cout, std::cin이 "이름공간 std에 접근해 각 ostream, istream 클래스로 정의된 객체 cout, cin을 사용한다" 라는 의미임을 알게 되었다.

profile
미생 개발자

0개의 댓글