c++ 形狀類Shape(派生出圓類Circle和矩形類Rectangle)
1.建立一個形狀類Shape作為基類,派生出圓類Circle和矩形類Rectangle,求出面積并獲取相關(guān)信息。
具體要求如下:
(1)形狀類Shape
(a)保護(hù)數(shù)據(jù)成員
double x,y:對于不同的形狀,x和y表示不同的含義,如對于圓,x和y均表示圓的半徑,而對于矩形,x表示矩形的長,y表示矩形的寬。訪問權(quán)限定義為保護(hù)類型是為了能被繼承下去,以便派生類能直接訪問x和y。
(b)公有成員函數(shù)
構(gòu)造函數(shù)Shape(double _x,double _y):用_x、_y分別初始化x、y。
double GetArea():求面積,在此返回0.0。
(2)圓類Circle,從Shape公有派生
(a)公有成員函數(shù)
Circle(double r):構(gòu)造函數(shù),并用r構(gòu)造基類的x和y。
double GetArea():求圓的面積。
double GetRadius():獲取圓的半徑。
(3)矩形類Rectangle,從Shape公有派生
(a)公有成員函數(shù)
Rectangle(double l,double w) :構(gòu)造函數(shù),并用l和w構(gòu)造基類的x和y。
double GetArea():求矩形的面積。
double GetLength():獲取矩形的長。
double GetWidth():獲取矩形的寬。
(4)在主函數(shù)中對派生類進(jìn)行測試。注意,在程序的開頭定義符號常量PI的值為3.14。
測試的輸出結(jié)果如下:
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;}//構(gòu)造函數(shù),并用r構(gòu)造基類的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;}//構(gòu)造函數(shù),并用l和w構(gòu)造基類的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; }
到此這篇關(guān)于c++ 形狀類Shape(派生出圓類Circle和矩形類Rectangle)的文章就介紹到這了,更多相關(guān)c++ 形狀類Shape內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++實現(xiàn)寢室衛(wèi)生管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C++實現(xiàn)寢室衛(wèi)生管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03用C語言求冪函數(shù)和指數(shù)函數(shù)的方法
這篇文章主要介紹了用C語言求冪函數(shù)和指數(shù)函數(shù)的方法,即pow()函數(shù)和sqrt()函數(shù)的使用,需要的朋友可以參考下2015-08-08centos 7 vscode cmake 編譯c++工程的教程詳解
這篇文章給大家介紹了centos 7 使用vscode+cmake配置簡單c++項目的方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2020-05-05