C++/디딤돌 C++

[C++ 소스] 집합 관계(Aggregation Relation), 필통과 연필

언제나휴일 2016. 12. 18. 22:16
반응형

[C++ 소스] 집합 관계(Aggregation Relation), 필통과 연필


Pencil.cpp

Pencil.h

PencilCase.cpp

PencilCase.h

Program.cpp


집합 관계 클래스 다이어그램



//Pencil.h

#pragma once

#include <iostream>

#include <string>

using namespace std;

class Pencil

{

    string company;

    int price;   

public:

    Pencil(string company,int price);

    string GetCompany()const;

    int GetPrice()const;

};


//Pencil.cpp

#include "Pencil.h"

 

Pencil::Pencil(string company,int price)

{

    this->company = company;

    this->price = price;

}

string Pencil::GetCompany()const

{

    return company;

}

int Pencil::GetPrice()const

{

    return price;

}


//PencilCase.h

#pragma once

#include "Pencil.h"

class PencilCase

{

    Pencil **base;

    const size_t capacity;

    size_t count;

public:

    PencilCase(size_t capacity);

    ~PencilCase(void);

    bool PushBack(Pencil *pencil);

    void List()const;

    size_t GetCount()const;

    Pencil *&operator[](size_t index);

};


//PencilCase.cpp

#include "PencilCase.h"

#include <iomanip>

using namespace std;

PencilCase::PencilCase(size_t capacity):capacity(capacity)

{

    base = new Pencil *[capacity];

    count = 0;

}

PencilCase::~PencilCase(void)

{

    delete[] base;

}

bool PencilCase::PushBack(Pencil *pencil)

{

    if(count<capacity)

    {

        base[count] = pencil;

        count++;

        return true;

    }

    return false;

}

 

void PencilCase::List()const

{

    //left:왼쪽 정렬, right:오른쪽 정렬, setw(n):폭을 n으로 설정

    cout<<left<<setw(10)<<"회사"<<right<<setw(5)<<"가격"<<endl;

    for(size_t i = 0; i<count; i++)

    {

        cout<<left<<setw(10)<<base[i]->GetCompany();

        cout<<right<<setw(5)<<base[i]->GetPrice()<<endl;

    }

}

 

size_t PencilCase::GetCount()const

{

    return count;

}

 

Pencil *&PencilCase::operator[](size_t index)

{

    if((index<0)||(index>=count))

    {

        throw "인덱스가 범위를 벗어났습니다.";

    }

    return base[index];

}


//Program.cpp

#include "PencilCase.h"

int main()

{   

    PencilCase pc(10);

 

    pc.PushBack(new Pencil("연필좋아",1000));

    pc.PushBack(new Pencil("연필나라",1200));

    pc.PushBack(new Pencil("연필좋아",1400));

    pc.PushBack(new Pencil("연필나라",1200));

    pc.PushBack(new Pencil("연필나라",1600));

    pc.PushBack(new Pencil("연필좋아",1100));

    pc.PushBack(new Pencil("연필나라",1300));

    pc.PushBack(new Pencil("연필좋아",1500));

    pc.PushBack(new Pencil("연필좋아",500));

    pc.List();

 

    size_t count = pc.GetCount();

    for(size_t i=0; i<count;i++)

    {

        delete pc[i];

    }

   

    return 0;

}


실행 결과

회사       가격

연필좋아   1000

연필나라   1200

연필좋아   1400

연필나라   1200

연필나라   1600

연필좋아   1100

연필나라   1300

연필좋아   1500

연필좋아    500 



본문

[디딤돌 C++] 62. 집합(AGGREGATION) 관계




반응형