C++ 23. 상속과 다형성 실습(도형)
- C++/설명
- 2016. 4. 20. 12:33
-상속과 다형성 실습 1. 도형
//Diagram.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Diagram
{
const int id;
static int last_id;
public:
Diagram();
virtual void Draw() = 0;
protected:
int GetID()const;
};
//Diagram.cpp
#include "Diagram.h"
Diagram::Diagram():id(last_id++)
{
}
void Diagram::Draw()
{
}
int Diagram::GetID()const
{
return id;
}
//Line.h
#pragma once
#include "Diagram.h"
#include "POint.h"
class Line : public Diagram
{
POint *p1;
POint *p2;
public:
Line(int x1, int y1, int x2, int y2);
virtual void Draw();
};
//Line.cpp
#include "Line.h"
#include "Diagram.h"
Line::Line(int x1, int y1, int x2, int y2)
{
p1 = new POint(x1,y1);
p2 = new POint(x2,y2);
}
void Line::Draw()
{
cout<<GetID()<<"선"<<endl;
cout<<"(x1 , y1)"<<endl;
p1->Draw();
cout<<"(x2 , y2)"<<endl;
p2->Draw();
}
//POint.h
#pragma once
#include "Diagram.h"
class POint:public Diagram
{
int x;
int y;
public:
POint(int x, int y);
virtual void Draw();
};
//POint.cpp
#include "POint.h"
int Diagram::last_id = 1;
POint::POint(int x, int y)
{
this->x = x;
this->y = y;
}
void POint::Draw()
{
cout<<GetID()<<"점"<<endl;
cout<<"x 좌표 :"<<x<<endl;
cout<<"y 좌표 :"<<y<<endl;
}
//REctangle.h
#pragma once
#include "Diagram.h"
#define interface struct
interface IGetArea
{
virtual int GetArea()const = 0; //순수 가상 메소드
};
class REctangle:public Diagram, public IGetArea
{
int bottom;
int left;
int right;
int top;
public:
REctangle(int left, int top, int right, int bottom);
void Draw();
int GetArea()const;
};
//REctangle.cpp
#include "REctangle.h"
#include "Diagram.h"
REctangle::REctangle(int left, int top, int right, int bottom)
{
this->left = left;
this->top = top;
this->right = right;
this->bottom = bottom;
}
void REctangle::Draw()
{
cout<<GetID()<<"사각형"<<endl;
cout<<"왼쪽 상단 좌표(left,top)"<<left<<","<<top<<endl;
cout<<"우측 하단 좌표(right,bottom)"<<right<<","<<bottom<<endl;
}
int REctangle::GetArea()const
{
int width = right - left;
if(width < 0)
{
width = -width;
}
int height = right - left;
if(height < 0)
{
height < 0;
}
return width * height;
}
//Program.cpp
#include "Diagram.h"
#include "POint.h"
#include "Line.h"
#include "REctangle.h"
void TestArea(IGetArea *iga)
{
cout<<"사각형의 넓이 : "<<iga->GetArea()<<endl;
}
int main(void)
{
Diagram *diagrams[3];
diagrams[0] = new POint(3,4);
diagrams[1] = new Line(0,0,5,5);
diagrams[2] = new REctangle(0,0,10,10);
for(int i = 0; i<3; i++)
{
diagrams[i]->Draw();
IGetArea *iga = dynamic_cast<IGetArea *>(diagrams[i]);
if(iga)
{
TestArea(iga);
}
cout<<endl;
}
for(int i = 0; i < 3; i++)
{
delete diagrams[i];
}
return 0;
}
'C++ > 설명' 카테고리의 다른 글
C++ 25. 상속과 다형성 최종실습(학생 프로그램) (0) | 2016.04.20 |
---|---|
C++ 24.상속과 다형성 실습2(상품, 할인상품) (0) | 2016.04.20 |
C++ 22. 파생 개체의 생성과 소멸 과정 (0) | 2016.04.19 |
C++ 21.추상 클래스 (0) | 2016.04.19 |
C++ 20. 인터페이스 (0) | 2016.04.19 |
이 글을 공유하기