7장 실습문제_1번
2020. 12. 29. 01:20ㆍC++
1. Book 객체에 대해 다음 연산을 하고자 한다.
Book a("청춘", 20000, 300), b("미래", 30000, 500);
a += 500;
b -= 500;
a.show();
b.show();
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 클래스의 멤버함수로 구현하라.
(2) +=,-=연산자 함수를 Book 클래스의 외부함수로 구현하라.
-답
(1)
#include <iostream>
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 x) { price += x; }
void operator-=(int x) { price -= x; }
};
int main() {
Book a("청춘", 20000, 300), b("미래", 30000, 500);
a += 500;
b -= 500;
a.show();
b.show();
}
(2)
#include <iostream>
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 &op,int x);
friend Book operator-=(Book &op,int x);
};
Book operator+=(Book &op,int x) {
op.price += x;
return op;
}
Book operator-=(Book& op, int x) {
op.price -= x;
return op;
}
int main() {
Book a("청춘", 20000, 300), b("미래", 30000, 500);
a += 500;
b -= 500;
a.show();
b.show();
}
'C++' 카테고리의 다른 글
8장. 상속 (0) | 2020.12.30 |
---|---|
7장 실습문제_2번 (0) | 2020.12.29 |
7장. 프렌드와 연산자 중복 (0) | 2020.12.29 |
6장 실습문제_5번 (0) | 2020.12.28 |
6장. 함수 중복과 static 멤버 (0) | 2020.12.28 |