继承实验2

题目:
以点(point)类为基类``,定义派生类:矩形类和圆类。
点为直角坐标点,矩形水平放置,由左下方的顶点和长宽定义。圆有圆心和半径定义。
派生类操作判断任一坐标点是在图形内,在图形的边缘上,还是在图形外。
默认初始化图形退化为点。
要求包括拷贝构造函数。编程测试类是否正确。

现来实现该实验:
`#include
using namespace std;
//定义基类点(Point)
class Point {
public:
int x, y;
Point(){}
Point(int x, int y);
};
Point::Point(int x, int y) {
this->x = x;
this->y = y;
}
//定义派生类矩形(Rectangle)
class Rectangle :public Point {
int lenth, width;
public:
Rectangle(int x, int y, int lenth, int width);
void Judge_Rec(Rectangle rec, int x, int y);
Rectangle(const Rectangle& rec);
};
Rectangle::Rectangle(int x, int y, int lenth, int width) :Point(x, y) {
this->lenth = lenth;
this->width = width;
}
void Rectangle::Judge_Rec(Rectangle rec, int x, int y) {
if (((x - rec.x == 0 || x - rec.x == rec.lenth) && ((y - rec.y) >= 0 && (y - rec.y) <= width)) || (((y - rec.y) == 0 || (y - rec.y) == width) && ((x - rec.x) >= 0 && (x - rec.x) <= lenth))) cout << “The point is on the edge of the rectangle!” << endl;
else if ((x - rec.x) < 0 || (x - rec.x) > lenth || (y - rec.y) < 0 || (y - rec.y) > width) cout << “The point is outside of the rectangle!” << endl;
else cout << “The point is inside of the rectangle!” << endl;
}
Rectangle::Rectangle(const Rectangle& rec) {
x = rec.x;
y = rec.y;
lenth = rec.lenth;
width = rec.width;
}
//定义派生类圆(Circle)
class Circle :public Point {
int radius;
public:
Circle(int x, int y, int radius);
void Judge_Cir(Circle cir, int x, int y);
Circle(const Circle& rec);
};
Circle::Circle(int x, int y, int radius) :Point(x, y) {
this->radius = radius;
}
void Circle::Judge_Cir(Circle cir, int x, int y) {
if ((x - cir.x) * (x - cir.x) + (y - cir.y) * (y - cir.y) - cir.radius * cir.radius == 0) cout << “The point is on the edge of the circle!” << endl;
else if ((x - cir.x) * (x - cir.x) + (y - cir.y) * (y - cir.y) - cir.radius * cir.radius >= 0) cout << “The point is outside of the circle!” << endl;
else cout << “The point is inside of the circle!” << endl;
}
Circle::Circle(const Circle& cir) {
x = cir.x;
y = cir.y;
radius = cir.radius;
}
int main() {
int x0 = 0, y0 = 0;//为方便观察实验将各图形左下角点定义为(0.0)
int x, y,lenth,width,radius;
cout << “The testing point:”;
cin >> x >> y;
cout << “The lenth of the rectangle:”;
cin >> lenth;
cout << “The width of the rectangle:”;
cin >> width;
Rectangle rec1(x0, y0, lenth, width);
rec1.Judge_Rec(rec1, x, y);
Rectangle rec2 = rec1;//拷贝一个矩形对象
rec2.Judge_Rec(rec2, x, y);
cout << “The radius of the circle:”;
cin >> radius;
Circle cir1(x0, y0, radius);
cir1.Judge_Cir(cir1, x, y);
Circle cir2 = cir1;//拷贝一个圆对象
cir2.Judge_Cir(cir2, x, y);
cout << “The testing is over!” << endl;
return 0;
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值