출처 : 윤성우의 열혈 c++ 프로그래밍
생성자 조건
#include <iostream>
using namespace std;
class SimpleClass
{
private:
int num;
public:
SimpleClass(int n) //생성자
{
num = n ;
}
int GetNum() const
{
return num;
}
};
// 생성자 생성 전 객체 생성 방법
SimpleClass sc;
SimpleClass *ptr = new SimpleClass;
// 생성자 생성 후 객채 생성 방법 (인자의 정보 추가 필요)
SimpleClass sc(20);
SimpleClass *ptr = new SimpleClass(30);
#include <iostream>
using namespace std;
class FruitSeller
{
private:
int APPLE_PRICE;
int numOfApples;
int myMoney;
public:
FruitSeller (int price, int num , int money)
{
APPLE_PRICE = price;
numOfApples = num;
myMoney = money;
}
int SalesQAppels(int money)
{
int num = money/APPLE_PRICE;
numOfApples -= num;
myMoney += money;
}
};
class FruitBuyer
{
private:
int myMoney;
int numOfApples;
public:
FruitBuyer(int money)
{
myMoney = money;
numOfApples = 0;
}
void BuyApples(FruitSeller &seller , int money)
{
numOfApples += seller.SalesQAppels(money);
myMoney -= money;
}
};
int main(void)
{
FruitSeller seller(2000, 20, 0);
FruitBuyer buyer(5000);
buyer.BuyApples(seller, 2000);
return 0 ;
}
#include <iostream>
using namespace std;
class Point
{
private:
int x;
int y;
public:
Point(const int &xpos, const int &ypos) // 생성자
int GetX() const;
int GetY() const;
bool SetX(int xpos);
bool SetY(int ypos);
};
#include <iostream>
#include "Point.h"
using namespace std;
Point :: Point(const int &xpos, const int &ypos)
{
x = xpos;
y = ypos;
}
// Get 함수는 '반환' Set 함수는 '저장'
int Point ::GetX() const // const 함수
{
return x;
}
int Point ::GetY() const
{
return y;
}
bool Point::SetX(int xpos)
{
if (xpos < 0 || xpos > 100)
{
cout << "잘못된 값 전달" << endl;
return false;
}
x = xpos;
return true;
}
bool Point::SetY(int ypos)
{
if (ypos < 0 || ypos > 100)
{
cout << "잘못된 값 전달" << endl;
return false;
}
y = ypos;
return true;
}
#include "Point.h"
class Rectangle
{
private:
Point upLeft;
Point lowRight;
public:
Rectangle(const int &x1 , const int &y1, const int &x2, const int &y2);
void ShowRecInfo() const;
};
: upleft (x1, y1) , lowRight(x2,y2)
#include <iostream>
#include "rectangle.h"
using namespace std;
Rectangle::Rectangle(const int &x1, const int &y1, const int &x2, const int &y2)
: upLeft(x1, y1), lowRight(x2, y2)
{
}
void Rectangle::ShowRecInfo() const
{
cout << "좌 상단: " << '[' << upLeft.GetX() << ",";
cout << upLeft.GetY() << ']' << endl;
cout << "우 하단: " << '[' << lowRight.GetX() << ",";
cout << lowRight.GetY() << ']' << endl;
}