#ifndef POINT_H
#define POINT_H
class Point
{
public:
Point(int x = 0, int y = 0);
Point(const Point& p);
int GetX();
int GetY();
~Point();
private:
int x;
int y;
};
#endif // !POINT_H
#include"Point.h"
Point::Point(int x, int y)
{
this->x = x;
this->y = y;
}
Point::Point(const Point& p)
{
this->x = p.x;
this->y = p.y;
}
int Point::GetX()
{
return this->x;
}
int Point::GetY()
{
return this->y;
}
Point::~Point()
{
}
#ifndef SHAPE_H
#define SHAPE_H
class Shape
{
public:
Shape(const char* c);
virtual void Show();//虚函数实现动态多态
void ShowColor();
~Shape();
private:
char color[10];
};
#endif // !SHAPE_H
#include"Shape.h"
#include<iostream>
using namespace std;
Shape::Shape(const char* c)
{
strcpy_s(color, strlen(c)+1, c);
}
void Shape::Show()
{
cout << "Draw a shape.The color is" << color << endl;
}
void Shape::ShowColor()
{
cout << color << endl;
}
Shape::~Shape()
{
}
#ifndef LINE_H
#define LINE_H
#include"Point.h"
#include"Shape.h"
class Line:public Shape
{
public:
Line(const Point& p1, const Point& p2, const char* c = "No data");
virtual void Show();//虚函数实现动态多态
~Line();
private:
Point start;
Point end;
};
#endif // !POINT_H
#include "Line.h"
#include<iostream>
using namespace std;
Line::Line(const Point& p1, const Point& p2, const char* c) :Shape(c)//,start(p1),end(p2)
{
this->start = p1;//this->start(p1)
this->end = p2;this->end(p2)
}
void Line::Show()
{
cout << "Draw a line from ("
<< this->start.GetX() << "," << this->start.GetY() << ") to ("
<< this->end.GetX() << "," << this->end.GetY() <<
"),with color ";
ShowColor();
}
Line::~Line()
{
}
#ifndef CIRCLE_H
#define CIRCLE_H
#include"Point.h"
#include"Shape.h"
class Circle :public Shape
{
public:
Circle(const Point& p, int r = 0, const char* c = "No date");
virtual void Show();//虚函数实现动态多态
~Circle();
private:
Point center;
int radius;
};
#endif // !CIRCLE_H
#include"Circle.h"
#include<iostream>
using namespace std;
Circle::Circle(const Point& p, int r, const char* c) :Shape(c), center(p)
{
this->radius = r;
}
void Circle::Show()
{
cout << "Draw a circle at center (" << this->center.GetX() << "," << this->center.GetY() << ")"
<< " with radius " << this->radius << " and color";
ShowColor();
}
Circle::~Circle()
{
}
#include"Circle.h"
#include"Line.h"
#include<iostream>
using namespace std;
int main()
{
Shape* ps[3];
Shape s("red");
Point p1(0, 0), p2(1, 1), p3(2, 2);
Line l(p1, p2, "blue");
Circle c(p3, 4, "yellow");
ps[0] = &s;
ps[1] = &l;
ps[2] = &c;
for (int i = 0; i < 3; i++)
{
ps[i]->Show();
}
/*
* 将成员函数声明为虚函数,在函数原型前面加virtual
* 定义基类指针,指向派生类对象,
* 在程序运行时,根据指针指向的具体对象来调用各自的虚函数。称为动态多态
*
*/
return 0;
}