Message Passing

Programming/C++ 2012. 5. 2. 22:30 |

관계를 형성하는 둘 이상의 클래스


하나의 독립된 클래스를 정의하는 것은 쉽다. 그러나 둘 이상의 클래스를 정의하되, 아래처럼 관계를 형성해서 정의하는 것은 쉽지 않다. 

하지만 이는 매우 중요하다. 단순히 함수호출로 이해하면 별 것 아니지만, 메시지 전달의 관점에서 보면 이는 매우 중요하다.


#include <iostream>

using namespace std;


class FruitSeller

{

private:

int numOfApple;

int totalMoney;

int APPLE_PRICE;

public:

void InitMember(int price, int num)

{

numOfApple = num;

APPLE_PRICE = price;

totalMoney = 0;

}

int SellFuit(int money)

{

int n = money/APPLE_PRICE;

numOfApple-=n;

totalMoney += money;

return n;

}

void ShowSeller(void)

{

cout<<"판매자의 남은 사과: "<<numOfApple<<endl;

cout<<"판매자의 현재 돈 : "<<totalMoney<<endl<<endl;

}

int gg;

};


class FruitBuyer

{

private:

int numOfApple;

int totalMoney;

public:

void InitMember(int money)

{

numOfApple = 0;

totalMoney = money;

}

void BuyFuit(FruitSeller &seller, int money) // 메시지 패싱. &를 이용하여 seller에게 접근(call-by-reference).

{

totalMoney -= money;

numOfApple += seller.SellFuit(money); //이 문장은 seller야 나에게 사과 2000원어치 줘라라는 뜻이된다.

}

void ShowBuyer(void)

{

cout<<"구매자의 소유한 사과: "<<numOfApple<<endl;

cout<<"구매자의 현재 돈 : "<<totalMoney<<endl<<endl;

}

};


int main(void)

{

FruitSeller seller;

seller.InitMember(1000, 20);

seller.ShowSeller();


FruitBuyer buyer;

buyer.InitMember(5000);

buyer.ShowBuyer();

buyer.BuyFuit(seller, 2000);  //seller에게 2000을 건내주고 있다.


seller.ShowSeller();

buyer.ShowBuyer();


return 0;

}



'Programming > C++' 카테고리의 다른 글

생성자(Constructor)  (0) 2012.05.12
캡슐화  (0) 2012.05.12
const 함수  (2) 2012.05.08
정보은닉(Information Hiding)  (0) 2012.05.03
클래스 기반의 두 가지 객체생성 방법  (0) 2012.05.02
Posted by scii
: