객체지향프로그래밍2 조교활동 기록

5주차 실습수업 기록 - 연산자 오버로딩

su0a 2024. 4. 14. 19:13

퀴즈 11. 입출력 연산자 오버로딩을 구현하는 걸 많은 학부생들이 어려워했다.

그래서 iclass에 입출력 연산자 오버로딩에 대해 글을 남겨논 글이 있는데 연산자 오버로딩을 이해하는데 어려움이 있는 다른 분들께 공유하고자 한다.

 

c++에서 자주 쓰는 cin,cout은 iostream라이브러리에 구현된 연산자 오버로딩을 사용하는 것입니다. 

cout을 예로 들어보겠습니다.

cout은 ostream클래스의 객체이고 ostream클래스는 출력을 수행하는 클래스입니다.

ostream 클래스 안에는 여러 자료형 타입에 대한 <<연산자 오버로딩이 구현되어 있습니다.

ostream타입의 객체가 출력 연산자<<를 만나면 출력연산자 우측에 있는 것을 인수로 하는 ostream클래스의 멤버 출력 연산자 오버로딩을 호출합니다.

ostream클래스의 멤버 출력 연산자 오버로딩은 우측에 있는 데이터를 호출하는 일을 합니다.

cout에 대해 클래스를 출력하는 오버로딩을 구현하고 싶으면 클래스를 인자로 하는 ostream에 대한 연산자 오버로딩을 구현하면 됩니다.

#include<iostream>
using namespace std;

class Power {
	int kick;
	int punch;
public:
	friend istream& operator>>(istream& is, Power& p);
	friend ostream& operator<< (ostream & os, Power & p);
	Power operator++(int n) {
		Power tmp = *this;
		this->kick++;
		this->punch++;
		return tmp;
	}
};

istream& operator>>(istream& is,Power& p) {
	char left_parenthesis, right_parenthesis, comma;
	is >> left_parenthesis >> p.kick >> comma >> p.punch >> right_parenthesis;
	return is;
}

ostream& operator<< (ostream& os, Power& p) {
	os << '(' << p.kick << ',' << p.punch << ')';
	return os;
}

int main() {
	Power p1, p2;
	cin >> p1;
	p2 = p1++;
	cout << p2;
}