栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

派生类及继承实现之虚函数

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

派生类及继承实现之虚函数

派生类及继承实现之虚函数
// 
题目描述


基类area_info 有两个派生类:rectangle 矩形类和三角形类 triangle,让每个派生类都包含函数:area()。
分别用来求解矩形的面积和三角形的面积。
要求:1、使用构造函数实现初始化。
2、输入值自己控制。
3、使用基类指针访问虚函数的方式(运行时多态,没有讲到,需要预习)求解矩形面积和三角形面积。
如下代码是开头部分,需要补充完善。 
#include 
using 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++代码:

// 
#include 
using 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;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/528929.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号