先定义一个点类point,包含数据成员x和y(坐标点)。以point类为基类,派生出矩形类Rectangle和圆类Circle。假设矩形水平放置,在Rectangle类中,继承来的基类中的点作为矩形左下方的顶点,在派生类中增加数据成员长和宽;在Circle类中,继承来的基类中的点作为圆点,在派生类中增加数据成员半径。
要求判断给定点位于矩形和圆的什么位置
#include <iostream>
using namespace std;
class point
{
public:
float x;
float y;
point(float a = 0.0, float b = 0.0) : x(a), y(b) {}
virtual void printLocation(point) { ; }
};
class Rectangle : public point
{
public:
float width;
float height;
Rectangle(float x, float y, float w, float h)
: point(x, y), width(w), height(h) {}
void printLocation(point p)
{
if (p.x > this->x && p.y > this->y && p.x < this->x + width && p.y < this->y + height)
cout << "Inside the rectangle\n";
else if (p.x < this->x || p.y < this->y || p.x > this->x + width || p.y > this->y + height)
{
cout << "Outside the rectangle\n";
}
else
{
cout << "On the rectangular\n";
}
}
};
class Circle : public point
{
public:
float radius;
Circle(float x, float y, float r)
: point(x, y), radius(r) {}
void printLocation(point p)
{
float sqrdis = (p.x - this->x) * (p.y - this->y) + (p.y - this->y) * (p.y - this->y);
if (sqrdis < radius * radius)
{
cout << "Inside the circle\n";
}
else if (sqrdis == radius * radius)
{
cout << "On the circle\n";
}
else
{
cout << "Outside the circle\n";
}
}
};
int main()
{
Rectangle r(0, 0, 5, 5);
r.printLocation(point(1, 2)); //Inside the rectangle
r.printLocation(point(0, 4)); //On the rectangular
r.printLocation(point(-1, 7)); //Outside the rectangle
Circle c(0, 0, 1);
c.printLocation(point(0, 1)); //On the circle
c.printLocation(point(0.5, 0.25)); //Inside the circle
c.printLocation(point(1, 1)); //Outside the circle
}
你看是不是要这样的