250x250
Notice
Recent Posts
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
관리 메뉴

일상 코딩

[C++/10.02] Composition 구성 관계 본문

C++/따배C++ 10강 객체들 사이의 관계

[C++/10.02] Composition 구성 관계

polarcompass 2021. 10. 31. 22:48
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