类的继承习题

来源:互联网 发布:淘宝店铺冻结怎么退货 编辑:程序博客网 时间:2024/06/05 03:04

建立一个形状类Shape作为基类,派生出圆类Circle和矩形类Rectangle,求出面积并获取相关信息。具体要求如下:
(1)形状类Shape
(a)保护数据成员
double x,y:对于不同的形状,x和y表示不同的含义,如对于圆,x和y均表示圆的半径,而对于矩形,x表示矩形的长,y表示矩形的宽。访问权限定义为保护类型是为了能被继承下去,以便派生类能直接访问x和y。
(b)公有成员函数
构造函数Shape(double _x,double _y):用_x、_y分别初始化x、y。
double GetArea():求面积,在此返回0.0。
(2)圆类Circle,从Shape公有派生
(a)公有成员函数
Circle(double r):构造函数,并用r构造基类的x和y。
double GetArea():求圆的面积。
double GetRadius():获取圆的半径。
(3)矩形类Rectangle,从Shape公有派生
(a)公有成员函数
Rectangle(double l,double w) :构造函数,并用l和w构造基类的x和y。
double GetArea():求矩形的面积。
double GetLength():获取矩形的长。
double GetWidth():获取矩形的宽。
(4)在主函数中对派生类进行测试。注意,在程序的开头定义符号常量PI的值为3.14。测试的输出结果如下:
circle:r=1, area=3.14
rectangle:length=3, width=4, area=12


程序代码:

#include "stdafx.h"

#include <iostream>
using namespace std;


class Shape
{
protected:
double x, y;
public:
Shape(){}
Shape(double _x, double _y) { x = _x; y = _y; }
virtual double GetArea() { return 0.0; }
};


class Circle :public Shape
{
public:
Circle(double a) :Shape(a,a){}
double GetArea()
{
double area;
area = 3.14*x*y;
return area;
}
double GetRadius(){ return x; }


};


class Rectangle :public Shape
{
public:
Rectangle(double _l, double _w) :Shape(_l, _w){}
double GetArea()
{
double area;
area = x * y;
return area;
}
double GetLength(){ return x; }
double GetWidth() { return y; }


};
int _tmain(int argc, _TCHAR* argv[])
{
Circle circle(1);
Rectangle rectange(3, 4);


cout << "radius =" << circle.GetRadius() << "   area =" << circle.GetArea() << endl;
cout << "length =" << rectange.GetLength()<<"   w ="<<rectange.GetWidth()<<"  area =" << rectange.GetArea() << endl;
system("pause");
return 0;
}
1 0
原创粉丝点击