// 题目描述 基类area_info 有两个派生类:rectangle 矩形类和三角形类 triangle,让每个派生类都包含函数:area()。 分别用来求解矩形的面积和三角形的面积。 要求:1、使用构造函数实现初始化。 2、输入值自己控制。 3、使用基类指针访问虚函数的方式(运行时多态,没有讲到,需要预习)求解矩形面积和三角形面积。 如下代码是开头部分,需要补充完善。 #includeusing namespace std; #include class area_info { public: area_info(double r, double s) { m_height = r; m_width = s; } virtual double area() = 0; protected: double m_height; double m_width; }; 输入 11.5 22.3 输出 正方形的面积为:256.45 三角形的面积为:128.225 样例输入 Copy 11.5 22.3 样例输出 Copy 正方形的面积为:256.45 三角形的面积为:128.225
C++代码:
// #includeusing namespace std; #include class area_info { public: area_info() {} area_info(double r, double s) { m_height = r; m_width = s; } virtual double area() = 0; protected: double m_height; double m_width; }; class triangle :public area_info { public: triangle(double height,double width) { m_height = height; m_width = width; } double area() { return (m_height * m_width) / 2; } }; class rectangle :public area_info { public: rectangle(double height, double width) { m_height = height; m_width = width; } double area() { return (m_height * m_width); } }; int main() { double a = 0.0, b = 0.0; cin>>a>>b; area_info* pArea = new rectangle(a,b); cout << "正方形的面积为:" << pArea->area() << endl; area_info* pArea1 = new triangle(a, b); cout << "三角形的面积为:" << pArea1->area() << endl; return 0; }



