#24 [c++] 연산자 재정의(<<,>>)

정상준·2022년 12월 2일
0

c++

목록 보기
20/25

📝 삽입 연산자(<<)와 추출 연산자(>>)

  • 삽입 연산자(<<)

    • insertion operator, 삽입자라고도 부름
      • <<연산자는 C++의 기본 연산자 : 정수 시프트 연산자
    • ostream 클래스에 중복 작성되어 있음
  • 추출 연산자(>>)

    • extraction operator
      • '>>연산자는 C++의 기본 연산자 : 정수 시프트 연산자
    • istream 클래스에 중복 작성되어 있음

✏️ 객체를 스트림에 출력하는 <<연산자

#include <iostream>
#include <iomanip>

using namespace std;

/*
(3,4)
(1,100)(2,200)
*/

class Point {
	int x, y;
public:
	Point(int x = 0, int y = 0) {
		this->x = x;
		this->y = y;
	}

	friend ostream& operator <<(ostream& stream, Point a);

};

ostream& operator <<(ostream& stream, Point a) {
	stream << "(" << a.x << "," << a.y << ")";
	return stream;
}

int main() {
	Point a(3, 4);
	cout << a << endl;

	Point q(1, 100), r(2, 200);
	cout << q << r << endl;
}

✏️ 객체를 입력 받는 >> 연산자

#include <iostream>
#include <iomanip>

using namespace std;

/*
x 좌표 >>100
y 좌표 >>200
(100,200)
*/

class Point {
	int x, y;
public:
	Point(int x = 0, int y = 0) {
		this->x = x;
		this->y = y;
	}

	friend ostream& operator <<(ostream& stream, Point a);
	friend istream& operator >>(istream& ist, Point &a);
};

ostream& operator <<(ostream& stream, Point a) {
	stream << "(" << a.x << "," << a.y << ")";
	return stream;
}

istream& operator >>(istream& ist, Point& a) {
	cout << "x 좌표 >>";
	ist >> a.x;
	cout << "y 좌표 >>";
	ist >> a.y;
	return ist;
}

int main() {
	Point p;
	cin >> p;
	cout << p;
}
profile
안드로이드개발자

0개의 댓글