溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用c++怎么創(chuàng)建一個形狀類Shape

發(fā)布時間:2020-11-30 15:06:16 來源:億速云 閱讀:322 作者:Leah 欄目:開發(fā)技術

使用c++怎么創(chuàng)建一個形狀類Shape?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

具體要求如下:

(1)形狀類Shape

(a)保護數(shù)據(jù)成員
double x,y:對于不同的形狀,x和y表示不同的含義,如對于圓,x和y均表示圓的半徑,而對于矩形,x表示矩形的長,y表示矩形的寬。訪問權限定義為保護類型是為了能被繼承下去,以便派生類能直接訪問x和y。
(b)公有成員函數(shù)
構造函數(shù)Shape(double _x,double _y):用_x、_y分別初始化x、y。
double GetArea():求面積,在此返回0.0。

(2)圓類Circle,從Shape公有派生

(a)公有成員函數(shù)
Circle(double r):構造函數(shù),并用r構造基類的x和y。
double GetArea():求圓的面積。
double GetRadius():獲取圓的半徑。

(3)矩形類Rectangle,從Shape公有派生

(a)公有成員函數(shù)
Rectangle(double l,double w) :構造函數(shù),并用l和w構造基類的x和y。
double GetArea():求矩形的面積。
double GetLength():獲取矩形的長。
double GetWidth():獲取矩形的寬。

(4)在主函數(shù)中對派生類進行測試。注意,在程序的開頭定義符號常量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;}//構造函數(shù),并用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;}//構造函數(shù),并用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;
}

關于使用c++怎么創(chuàng)建一個形狀類Shape問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業(yè)資訊頻道了解更多相關知識。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI