명품C++프로그래밍

명품 C++ Programming 실습문제 7장 2번

anycoding 2021. 5. 20. 19:29
반응형

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

 

2. Book 객체를 활용하는 사례이다.

int main() {
	Book a("명품 C++", 30000, 500), b("고품 C++", 30000, 500);
	if (a == 30000)cout << "정가 30000원" << endl;       //price비교
	if (a == "명품 C++")cout << "명품 C++ 입니다." << endl; //책 title 비교
	if (a == b)cout << "두 책이 같은 책입니다." << endl; //title,price,pages 모두 비교
}

 

결과

정가 30000원

명품 C++입니다.

 

1. 세 개의 == 연산자를 함수를 가진 Book 클래스를 작성하라.

#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 a);
	bool operator==(string str);
	bool operator==(Book& a);
};
bool Book::operator==(int a)
{
	if (price == a)
		return true;
	else
		return false;
}
bool Book::operator==(string str)
{
	if (title == str)
		return true;
	else
		return false;
}
bool Book::operator==(Book b)
{
	if (price == b.price && title == b.title && pages == b.pages)
		return true;
	else
		return false;
}
int main() {
	Book a("명품 C++", 30000, 500), b("고품 C++", 30000, 500);
	if (a == 30000)cout << "정가 30000원" << endl;       //price비교
	if (a == "명품 C++")cout << "명품 C++ 입니다." << endl; //책 title 비교
	if (a == b)cout << "두 책이 같은 책입니다." << endl; //title,price,pages 모두 비교
}

 

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 a);
	friend bool operator==(Book a, string str);
	friend bool operator==(Book a, Book b);
};
bool operator==(Book a, int b)
{
	if (a.price == b)
		return true;
	else
		return false;
}
bool operator==(Book a, string str)
{
	if (a.title == str)
		return true;
	else
		return false;
}
bool operator==(Book a, Book& b)
{
	if (a.price == b.price && a.title == b.title && a.pages == b.pages)
		return true;
	else
		return false;
}
int main() {
	Book a("명품 C++", 30000, 500), b("고품 C++", 30000, 500);
	if (a == 30000)cout << "정가 30000원" << endl;       //price비교
	if (a == "명품 C++")cout << "명품 C++ 입니다." << endl; //책 title 비교
	if (a == b)cout << "두 책이 같은 책입니다." << endl; //title,price,pages 모두 비교
}

 

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

반응형