1. 程式人生 > >第十一週上機實踐專案4——類族的設計(3)

第十一週上機實踐專案4——類族的設計(3)

(3)再以Circle類為直接基類,派生出一個Cylinder(圓柱體)類,再增加資料成員h(高),,以及求圓柱表面積的成員函式area和求圓柱體積的成員函式volume,實現需要的成員函式,並設計main函式完成測試。

程式碼

#include<iostream>
#include<Cmath>
using namespace std;
class Point
{
protected:
    double x,y;
public:
    Point(double xx,double yy):x(xx),y(yy){}
    double getx()
    {
        return
x; } double gety() { return y; } void show1(); }; void Point::show1() { cout<<"底面圓心座標:"<<"("<<x<<","<<y<<")"<<endl; } class Circle:public Point { protected: double r,area; public: Circle(double xx,double yy,double rr):Point
(xx,yy),r(rr){} double getarea(); void show2(); double getr() { return r; } }; double Circle::getarea() { area=r*r*3.14; return area; } void Circle::show2() { show1(); cout<<"底面積:"<<getarea()<<endl; } class Cylinder:public Circle { protected
: double h,volume; public: Cylinder(double xx,double yy,double rr,double hh):Circle(xx,yy,rr),h(hh){} double getvolume(); friend ostream &operator<<(ostream &out,Cylinder &c); double geth() { return h; } }; double Cylinder::getvolume() { volume=getarea()*h; return volume; } ostream &operator<<(ostream &out,Cylinder &c) { c.show2(); out<<"體積:"<<c.getvolume()<<endl; return out; } int main() { Cylinder c(2.2,3.3,4.4,5.5); cout<<"該圓柱體的屬性:"<<endl; cout<<"底面半徑:"<<c.getr()<<endl; cout<<"高:"<<c.geth()<<endl; cout<<c; return 0; }

執行結果:這裡寫圖片描述