Kong Eunho

프렌드와 연산자 중복

2025년 10월 02일 09시
카테고리 - LECTURE, 객체지향프로그래밍II


객체지향프로그래밍II(김정준) 5주차 강의내용

친구
내 가족의 일원은 아니지만 내 가족과 동일한 권한을 가진 일원으로 인정받은 사람

C++ 프렌드

프렌드로 초대하는 3가지 유형
◼ 전역 함수 : 클래스 외부에 선언된 전역 함수
◼ 다른 클래스의 멤버 함수 : 다른 클래스의 특정 멤버 함수
◼ 다른 클래스 전체 : 다른 클래스의 모든 멤버 함수

연산자 중복

연산자 중복의 특징

연산자 함수

▼ 연산자 함수 구현 예제

class Power {
	int kick;
	int punch;
public:
	Power(int kick = 0, int punch = 0) {
		this->kick = kick;
		this->punch = punch;
	}
	void show();
	Power operator+ (Power op2);
	Power operator+ (int op2);
	friend Power operator+ (int op1, Power op2);
	bool operator== (Power op2);
	Power& operator+= (Power op2);
	Power& operator++ ();
	Power operator++ (int x);
	Power& operator<< (int n);
};

void Power::show() {
	cout << "kick = " << kick << ',' << "punch = " << punch << endl;
}

Power Power::operator+(Power op2) {
	Power tmp;
	tmp.kick = this->kick + op2.kick;
	tmp.punch = this->punch + op2.punch;
	return tmp;
}

Power Power::operator+(int op2) {
	Power tmp;
	tmp.kick = kick + op2;
	tmp.punch = punch + op2;
	return tmp;
}

Power operator+(int op1, Power op2) {
	Power tmp;
	tmp.kick = op1 + op2.kick;
	tmp.punch = op1 + op2.punch;
	return tmp;
}

bool Power::operator==(Power op2) {
	if (kick == op2.kick && punch == op2.punch)return true;
	else return false;
}

Power& Power::operator+=(Power op2) {
	kick += op2.kick;
	punch += op2.punch;
	return *this;
}

Power& Power::operator++() {
	kick++;
	punch++;
	return *this;
}

Power Power::operator++(int x) {
	Power tmp = *this;
	kick++;
	punch++;
	return tmp;
}

Power& Power::operator<<(int n) {
	kick += n;
	punch += n;
	return *this;
}
◀ 이전 글 LECTURE, 인공지능개론
탐색 2
2025-09-30
목록으로 다음 글 ▶ COTE
선교사와 식인종
2025-10-04