일상 코딩
[C++/10.02] Composition 구성 관계 본문
728x90
1. main.cpp
최대한 클래스 작동 부분이 안 나타나는게 좋다.
세부적인 구현은 header file에서 전부 구현하고
함수만 쓸 수 있도록 한다.
#include "Monster.h"
using namespace std;
int main()
{
Monster mon1("Sanson", Position2D(0,0));
// mon1.m_location;
cout << mon1 << endl;
Monster mon2("Sanson", Position2D(0, 0));
cout << mon2 << endl;
//while(1) game loop
{
// event
mon1.moveTo(Position2D(1,1));
cout << mon1 << endl;
}
return 0;
}
2. Monster.h (header file class)
#pragma once
#include <string>
#include "Position2D.h"
class Monster
{
private:
std::string m_name; // char * data, unsigned length;
Position2D m_location;
// int m_x; // location
// int m_y;
public:
Monster(const std::string name_in, const Position2D &pos_in)
: m_name(name_in),
m_location(pos_in)
{
}
void moveTo(const Position2D &pos_target)
{
m_location.set(pos_target);
// m_x = x_target;
// m_y = y_target;
}
friend std::ostream &operator<<(std::ostream &out, const Monster &monster)
{
out << monster.m_name << " " << monster.m_location;
return out;
}
};
3. Position2D.h (Position header class)
#pragma once
#include <iostream>
class Position2D
{
private:
int m_x;
int m_y;
public:
Position2D(const int &x_in, const int &y_in)
: m_x(x_in), m_y(y_in)
{
}
// TODO: overload operator =
void set(const Position2D &pos_target)
{
set(pos_target.m_x, pos_target.m_y);
}
void set(const int &x_target, const int &y_target)
{
m_x = x_target;
m_y = y_target;
}
friend std::ostream &operator<<(std::ostream &out, const Position2D &pos2d)
{
out << pos2d.m_x << " " << pos2d.m_y;
return out;
}
};
728x90
'C++ > 따배C++ 10강 객체들 사이의 관계' 카테고리의 다른 글
[C++/10.05] 의존 관계, Dependecy on, Timer, Chrono (0) | 2021.11.03 |
---|---|
[C++/10.04] 제휴 관계, Association (0) | 2021.11.03 |
[C++/10.03] Aggregation 집합 관계 (0) | 2021.11.02 |