1. 문제
Book 객체를 활용하는 사례이다.
(1) 세 개의 == 연산자 함수를 가진 Book 클래스를 작성하라.
(2) 세 개의 == 연산자를 프렌드 함수로 작성하라.
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; }
bool operator == (int n) {
if( price == n ) return true;
else return false;
}
bool operator == (string n) {
if( title == n ) return true;
else return false;
}
bool operator == (Book n) {
if( title == n.title && price == n.price && pages == n.pages ) return true;
else return false;
}
};
int main() {
Book a("명품 C++", 30000, 500), b("고품 C++", 30000, 500);
if( a == 30000 ) cout << "정가 30000원" << endl;
if( a == "명품 C++" ) cout << "명품 C++ 입니다." << endl;
if( a == b ) cout << "두 책이 같은 책입니다." << endl;
}
** 연산자를 오버로딩해서 매개 변수가 다른 함수 3개를 중복 구현합니다.
(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 bool operator == (Book b, int n);
friend bool operator == (Book b, string n);
friend bool operator == (Book b1, Book b2);
};
bool operator == (Book b, int n) {
if( b.price == n ) return true;
else return false;
}
bool operator == (Book b, string n) {
if( b.title == n ) return true;
else return false;
}
bool operator == (Book b1, Book b2) {
if( b1.title == b2.title && b1.price == b2.price && b1.pages == b2.pages ) return true;
else return false;
}
int main() {
Book a("명품 C++", 30000, 500), b("고품 C++", 30000, 500);
if( a == 30000 ) cout << "정가 30000원" << endl;
if( a == "명품 C++" ) cout << "명품 C++ 입니다." << endl;
if( a == b ) cout << "두 책이 같은 책입니다." << endl;
}
**위 문제의 기능을 프렌드 함수로 수정하면 되겠습니다.
프렌드 함수로 수정하면서 book b의 변수를 매개 변수로 추가적으로 받아야 하는 점에서 차이가 있습니다.
'programming > 명품 C++ programming' 카테고리의 다른 글
명품 C++ programming 실습 문제 7장 5번 (0) | 2020.08.16 |
---|---|
명품 C++ programming 실습문제 7장 4번 (0) | 2020.08.15 |
명품 C++ programming 실습문제 7장 3번 (0) | 2020.08.15 |
명품 C++ programming 실습문제 7장 1번 (0) | 2020.08.15 |
명품 C++ programming 실습 문제 6장 1번 (0) | 2020.08.15 |
댓글