美文网首页
c++多态例子

c++多态例子

作者: 一路向后 | 来源:发表于2021-08-13 21:29 被阅读0次

1.源码实现

#include <iostream>

using namespace std;

class Shape {
public:
    Shape(int a, int b)
    {
        width = a;
        height = b;
    }

    /*int area()
    {
        cout << "Parent class area: " << endl;
        return 0;
    }*/
    virtual int area() = 0;

protected:
    int width;
    int height;
};

class Rectangle : public Shape {
public:
    Rectangle(int a, int b) : Shape(a, b){}
    int area()
    {
        cout << "Rectangle class area: " << width * height << endl;
        return width * height;
    }
};

class Triangle : public Shape {
public:
    Triangle(int a, int b) : Shape(a, b){}
    int area()
    {
        cout << "Triangle class area: " << width * height / 2 << endl;
        return width * height / 2;
    }
};

int main()
{
    Shape *shape;
    Rectangle rec(10, 7);
    Triangle tri(10, 5);

    shape = &rec;

    //调用矩形的求面积函数
    shape->area();

    shape = &tri;

    //调用三角形的求面积函数
    shape->area();

    return 0;
}

2.编译源码

$ g++ -o example example.cpp

3.运行及其结果

$ ./example
Rectangle class area: 70
Triangle class area: 25

相关文章

  • c++多态例子

    1.源码实现 2.编译源码 3.运行及其结果

  • C++中多态实现的例子

    先看一段代码 实际运行结果,都是调用Base的Run方法,预期是p调用Base,d调用Dervie。原来具体执行哪...

  • 深刻剖析之c++博客文章

    三大特性 封装、继承、多态 多态 C++ 虚函数表解析C++多态的实现原理 介绍了类的多态(虚函数和动态/迟绑定)...

  • C++泛型与多态(3):类模板特化

    C++的类没有重载,所以类只能依靠特化来实现多态。 例子:斐波那契数列 斐波那契数列(Fibonacci Numb...

  • 十九、多态例子

    1动物园 2电脑组装的案例 3.企业员工信息管理系统 一个小型公司的人员信息管理系统某小型公司,主要有四类人员:经...

  • 多态的C++实现

    多态的C++实现 1 多态的原理 什么是多态?多态是面向对象的特性之一,只用父类指针指向子类的对象。 1.1 多态...

  • C++ 的多态(Polymorphism), virtual f

    多态 c++支持两种多态,编译时多态和运行时多态但其实编译时多态根本不是真正的多态,编译时多态就是函数的重载,ov...

  • 慕课网-C++远征之多态篇(中)-学习笔记

    c++远征之多态篇 纯虚函数 & 抽象类 例子: 纯虚函数: 没有函数体 直接等于0 在虚函数表中直接写为0, 包...

  • scala中的多态 Ad-hoc polymorphism和ty

    多态的类型(polymorphism) (1) parametric多态 下面例子来自scalaz教程: scal...

  • C++第六篇多态

    C++中的多态性分为编译时多态性和运行时多态性,编译时多态通过函数重载和模板体现,运行多态通过虚函数体现编译、连接...

网友评论

      本文标题:c++多态例子

      本文链接:https://www.haomeiwen.com/subject/rqbjbltx.html