반응형

1~4번 까지 쓰일 Book 클래스입니다.

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; }
};

 

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

int main()
{
	Book a("청춘", 20000, 300), b("미래", 30000, 500);
	a += 500; // 책 a의 가격 500원 증가
	b -= 500; // 책 b의 가격 500원 감소
	a.show();
	b.show();
	return 0;
}

 

결과

청춘 20500원 300 페이지

미래 29500원 500 페이지

 

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

#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; }
    Book& operator+= (int a);
	Book& operator-= (int a);
};
Book& Book::operator+=(int a)
{
	price += a;
	return *this;
}
Book& Book::operator-=(int a)
{
	price -= a;
	return *this;
}
int main()
{
	Book a("청춘", 20000, 300), b("미래", 30000, 500);
	a += 500;
	b -= 500;
	a.show();
	b.show();
	return 0;
}

 

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

#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 a);
	friend Book operator-=(Book& b, int a);
};
Book operator+=(Book& b, int a)
{
	b.price += a;
	return b;
}
Book operator-=(Book& b, int a)
{
	b.price -= a;
	return b;
}
int main()
{
	Book a("청춘", 20000, 300), b("미래", 30000, 500);
	a += 500;
	b -= 500;
	a.show();
	b.show();
	return 0;
}

 

오류 또는 수정 사항 궁금한 점 있으시면 댓글로 남겨주세요.

반응형

+ Recent posts