第十六週(OJ 練習一 7)——抽象基類。
阿新 • • 發佈:2019-01-08
/* 02.*煙臺大學計算機學院學生 03.*All right reserved. 04.*檔名稱*煙臺大學計算機學院學生 05.*All right reserved. 06.*檔名稱:抽象基類 07.*作者:王洪海 08.*完成日期:2013年6月12日 09.*版本號:v1.0 10.*對任務及求解方法的描述部分:抽象基類 11.*我的程式: 12.*/ /* C++程式碼 */ #include <iostream> #include <iomanip> using namespace std; class Shape { public: virtual double area() =0; }; class Circle:public Shape { public: Circle(double r):radius(r){} ~Circle(){} double area() { return 3.141596*radius*radius; } private: double radius; }; class Rectangle:public Shape { public: Rectangle(double l,double w):length(l),width(w){} ~Rectangle(){} double area() { return length*width; } private: double length; double width; }; class Triangle:public Shape { public: Triangle(double h,double d):height(h),down(d){} ~Triangle(){} double area() { return down*height*0.5; } private: double down; double height; }; void printArea(Shape &n) { cout<< setiosflags(ios::fixed)<<setprecision(2)<<n.area()<<endl; } int main() { float r,a,b,w,h; cout<<fixed<<setprecision(2); cin>>r; Circle circle(r); cout<<"area of circle = "; printArea(circle); cin>>a>>b; Rectangle rectangle(a,b); cout<<"area of rectangle = "; printArea(rectangle); cin>>w>>h; Triangle triangle(w,h); cout<<"area of triangle = "; printArea(triangle); return 0; }
執行結果,如下圖:
對抽象基類又熟悉了一次!!!