2773 - 长方体体积(继承和派生)
时间限制 : 1 秒
内存限制 : 128 MB
定义一个Rectangle(长方形)类,它包含两个数据成员长和宽;以及包含用于求长方形面积的成员函数CalArea()。
再定义Rectangle的派生类Rectangular(长方体),它包含一个新数据成员高度和用来求长方体体积的成员函数CalVolume()。
在main函数中,分别使用这两个类求某个长方形的面积和某个长方体的体积。
主函数如下:
int main()
{
double length,width,height;
cin>>length>>width;
Rectangle rectangle(length,width);
cout<<rectangle.CalArea()<<endl;
cin>>length>>width>>height;
Rectangular rectangular(length, width, height);
cout<<rectangular.CalVolume()<<endl;
return 0;
}
题目输入
输入数据有二行,第一行2个空格分隔的整数,表示矩形的长和宽,第二行3个空格分隔的整数,代表长方体的长宽高。
题目输出
输出数据2行,输出长方体的底面积和体积。
输入/输出样例
输入格式
3 4 3 4 5
输出格式
12 60
C++解答
#include <iostream> using namespace std; class Rectangle { public: Rectangle(double l, double w); Rectangle() {} double CalArea(); protected: double length; double width; }; class Rectangular:public Rectangle { public: Rectangular(double l, double w, double h); double CalVolume(); private: double height; }; Rectangle::Rectangle(double l, double w) { length = l; width = w; } Rectangular::Rectangular(double l, double w, double h):Rectangle(l,w),height(h) {} double Rectangle::CalArea() { return length*width; } double Rectangular::CalVolume() { return height*width*length; } int main() { double l,w,h; cin>>l>>w; Rectangle rectangle(l,w); cout<<rectangle.CalArea()<<endl; cin>>l>>w>>h; Rectangular rectangular(l, w, h); cout<<rectangular.CalVolume()<<endl; return 0; }