Description
阮宝同学期待着暑假来临,知道C++不好好复习麻烦不小。没有多态性,那就不叫面向对象,老师不划重点也能猜到。嘿嘿,自己做个经典题,怎么变题也不怕。老湿,再难的题还有木有?
Input
输入四个数,前两个是矩形的长和宽,后两个是三角形的底边长和高。
Output
分两行输出两个数,第一个是矩形的面积,第二个是三角形的面积。
Sample Input
3.5 6.4
3.5 6.4
Sample Output
22.4
11.2
#include<iostream> using namespace std; class Shape { public: double virtual area()=0; }; class Rectangle:public Shape { public: Rectangle(double a,double b); double area(); private: double length; double width; }; Rectangle::Rectangle(double a,double b):length(a),width(b){} double Rectangle::area() { return length*width; } class Triangle:public Shape { public: Triangle(double a,double b):len(a),wid(b){} double area() { return (len*wid)/2; } private: double len,wid; }; int main() { double a,b; cin>>a>>b; //输入矩形的长和宽 Rectangle r(a,b);//建立Rectangle类对象r, 矩形长a宽b Shape *s1=&r; cout<<s1->area()<<endl;//输出矩形的面积 double w,h; cin>>w>>h; //输入矩形的长和宽 Triangle t(w,h); //建立Triangle类对象t,三角形底边长w高h Shape &s2=t; cout<<s2.area();//输出三角形面积 return 0; }