建立一個形狀類Shape作爲基類,派生出圓類Circle和矩形類Rectangle,求出面積並獲取相關信息。具體要求如下:

1.建立一個形狀類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;
#define PI 3.14
class Shape
{
public:
	Shape(){}
	Shape(double _x,double _y):x(_x),y(_y){}
	double GetArea();
protected:
	double x,y;

};
double Shape::GetArea()
{
	return 0.0;
}
class Circle:public Shape
{
public:
	Circle(){}
	Circle(double r){ x=r;}//構造函數,並用r構造基類的x和y。
    double GetArea();//求圓的面積。
    double GetRadius();//獲取圓的半徑。
};

double Circle::GetArea()
{
	return PI*x*x;
}
double Circle::GetRadius()
{
	return x;
}

class Rectangle:public Shape
{
public:
	Rectangle(){}
	Rectangle(double l,double w){x = l;y=w;}//構造函數,並用l和w構造基類的x和y。
   double GetArea();//求矩形的面積。
   double GetLength();//獲取矩形的長。
   double GetWidth();//獲取矩形的寬

};
 double Rectangle::GetArea()
 {
	 return x*y;
 }
 double Rectangle::GetLength()
 {
	 return y;
 }
  double Rectangle::GetWidth()
 {
	 return x;
 }
int main(int argc, _TCHAR* argv[])
{
	
	Circle circle(1);
	
	cout<<"  Radius="<<circle.GetRadius()<<"  area="<<circle.GetArea()<<endl;
	Rectangle rectangle(3,4);

	cout<<"  Length="<<rectangle.GetLength()<<"  Width="<<rectangle.GetWidth()<<"  area="<<rectangle.GetArea()<<endl;
	return 0;
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章