C++/clone code

[C++] market.cpp (객체와 클래스에 대한 이해)

year.number 2022. 6. 28. 19:39

 

Power C++ p.387

[목표] 사용자로부터 2개의 상품에 대한 정보를 입력받고, 더 저렴한 상품을 비교하여 출력한다.

 

#include <iostream>
#include <string>
#include<iomanip>

using namespace std;

class Product {
private:
	int id;
	string name;
	int price;

public:
	void input();
	void print();
	bool isCheaper(Product other);

};

void Product::input() {
	cout << "\n< 상품정보 입력 >\n";
	cout << setw(5) << "일련번호: ";
	cin >> id;
	cout << setw(5) << "이름: ";
	cin >> name;
	cout << setw(5) << "가격: ";
	cin >> price;
}

void Product::print() {
	cout << setw(5) << "일련번호: " << id << endl;
	cout << setw(5) << "이름: " << name << endl;
	cout << setw(5) << "가격: " << price << endl;
}

bool Product::isCheaper(Product other) {
	if (price < other.price)
		return true;
	else
		return false;
}

int main() {
	Product market1, market2;

	market1.input();
	market2.input();

	if (market1.isCheaper(market2)) {
		market1.print();
		cout << "이 더 쌉니다.\n";
	}
	else {
		market2.print();
		cout << "이 더 쌉니다.\n";
	}

	return 0;
}

Key Point 

bool isCheaper(Product other) 함수는 객체를 함수의 매개 변수로 이용한다.

bool Product::isCheaper(Product other) {
	if (price < other.price)
		return true;
	else
		return false;
}

출력결과