본문 바로가기
programming/명품 C++ programming

명품 C++ programming 실습문제 7장 1번

by doachy 2020. 8. 15.

1. 문제

Book 객체에 대해 다음 연산을 하고자 한다.

 

(1) +=, -= 연산자 함수를 Book 클래스의 멤버 함수로 구현하라.

 

(2) +=, -= 연산자 함수를 Book 클래스 외부 함수로 구현하라.

 

2. 결과

 

3. 코드

(1)

#include <iostream>
#include <string>
using namespace std;

class Book {
	string title;
	int price, pages;
public : 
	Book(string title="", int price=0, int pages=0) {
		this->title = title; this->price = price; this->pages = pages;
	}
	void show() {
		cout << title << ' ' << price << "원 " << pages << " 페이지" << endl;
	}
	string getTitle() { return title; }
	void operator +=(int n) { price += n; }
	void operator -=(int n) { price -= n; }
};

int main() {
	Book a("청춘", 20000, 300), b("미래", 30000, 500);
	a += 500;
	b -= 500;
	a.show();
	b.show();
}

** operator를 사용해서 클래스의 멤버 함수로 구현하였다.

 

 

 

(2)

#include <iostream>
#include <string>
using namespace std;

class Book {
	string title;
	int price, pages;
public : 
	Book(string title="", int price=0, int pages=0) {
		this->title = title; this->price = price; this->pages = pages;
	}
	void show() {
		cout << title << ' ' << price << "원 " << pages << " 페이지" << endl;
	}
	string getTitle() { return title; }
	friend Book operator +=(Book &b, int n);
	friend Book operator -=(Book &b, int n);
};
Book operator +=(Book &b, int n) {
	b.price += n; 
	return b;
}
Book operator -=(Book &b, int n) { 
	b.price -= n; 
	return b;
}

int main() {
	Book a("청춘", 20000, 300), b("미래", 30000, 500);
	a += 500;
	b -= 500;
	a.show();
	b.show();
}

** 클래스 외부 함수로 구현해야 하기 때문에 프렌드 함수로 구현해야한다.

프렌드 함수로 구현할 시에는 외부 함수이므로 b를 참조 변수로 선언해야 한다는 점에서 차이가 있다.

댓글