類的繼承習題

建立一個形狀類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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章