반응형
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; }
}
다음 연산을 통해 책의 제목을 사전 순으로 비교하고자 한다. <연산자를 작성하라.
int main()
{
Book a("청춘", 20000, 300);
string b;
cout << "책 이름을 입력하세요 >> ";
getline(cin, b); //키보드로부터 문자열로 책 이름을 입력받음
if (b < a)
cout << a.getTitle() << "이 " << b << "보다 뒤에 있구나!" << endl;
}
결과
책 이름을 입력하세요>>바람과 함께 사라지다
청춘이 바람과 함께 사라지다보다 뒤에 있구나!
소스코드(friend 함수 사용)
#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<(string b, Book a);
};
bool operator<(string b, Book a)
{
if (b < a.title)
return true;
else
return false;
}
int main()
{
Book a("청춘", 20000, 300);
string b;
cout << "책 이름을 입력하세요 >> ";
getline(cin, b); //키보드로부터 문자열로 책 이름을 입력받음
if (b < a)
cout << a.getTitle() << "이 " << b << "보다 뒤에 있구나!" << endl;
}
반응형
'명품C++프로그래밍' 카테고리의 다른 글
명품 C++ Programming 실습문제 7장 6번 (0) | 2021.05.20 |
---|---|
명품 C++ Programming 실습문제 7장 5번 (0) | 2021.05.20 |
명품 C++ Programming 실습문제 7장 3번 (0) | 2021.05.20 |
명품 C++ Programming 실습문제 7장 2번 (0) | 2021.05.20 |
명품 C++ Programming 실습문제 7장 1번 (0) | 2021.05.20 |