zoukankan      html  css  js  c++  java
  • 多态原理和多态实例

    多态实现的关键------虚函数表

    每一个有虚函数的类(或有虚函数的类的派生类)都有一个虚函数表,该类的任何对象中都放着虚函数表的指针。虚函数表中列出了该类的虚函数地址。多出来的4个字节就是用来存放虚函数表的地址的。

     

    多态的函数调用语句被编译成一系列根据基类指针所指向的(或基类引用所引用的)对象中存放的虚函数表的地址,在虚函数表中查找虚函数地址,并调用虚函数的指令。

    多态在使用中会带来空间上额外的空间开销和时间开销。每个有虚函数类的对象中会多出4个字节来存放虚函数表的地址。

    多态处理图形类的代码:

    #include <iostream>
    #include <math.h>
    #include <string>
    using namespace std;
    
    class shape
    {
    public:
        virtual double area() = 0;//纯虚函数
        virtual void printInfo() = 0;
    };
    
    class circle :public shape
    {
    public:
        int r;
        virtual double area()
        {
            return (3.14*r*r);
        }
        virtual void printInfo()
        {
            cout << "circle" << area() << endl;
        }
    };
    class rectangle :public shape
    {
    public:
        int w, h;
        virtual double area()
        {
            return(w*h);
        }
        virtual void printInfo()
        {
            cout << "rectangle" << area() << endl;
        }
    };
    class triangle :public shape
    {
    public:
        int a, b, c;
        virtual double area()
        {
            double length = (a + b + c) / 2;
            return(sqrt((length - a)*(length - b)*(length - c)));
        }
        virtual void printInfo()
        {
            cout << "triangle" << area() << endl;
        }
    };
    int mycompare(const void *s1, const void *s2)
    {
        shape **p1, **p2;
        p1 = (shape **)s1;
        p2 = (shape **)s2;
        if ((*p1)->area() > (*p2)->area())
            return 1;
        if ((*p1)->area() < (*p2)->area())
            return -1;
        else
            return 0;
    }
    int main()
    {
        int n = 0; char s = ' ';
        shape *c[50]; circle *pc = NULL; 
        rectangle *pr = NULL; triangle *pt = NULL;
        cin >> n;
        for (int i = 0; i < n; i++)
        {
            cin >> s;
            switch (s)
            {
            case 'c':
                pc = new circle();
                cin >> pc->r;
                c[i] = pc;
                break;
            case 'r':
                pr = new rectangle;
                cin >> pr->h >> pr->w;
                c[i] = pr;
                break;
            case 't':
                pt = new triangle;
                cin >> pt->a >> pt->b >> pt->c;
                c[i] = pt;
                break;
            default:
                break;
            }
        }
        qsort(c, n, sizeof(shape*), mycompare);
        for (int i = 0; i < n; i++)
            c[i]->printInfo();
        return 0;
    }

     参考链接:

    https://www.coursera.org/learn/cpp-chengxu-sheji

  • 相关阅读:
    echarts各个配置项详细说明总结
    享元模式
    观察者模式
    策略模式
    桥接模式
    适配器模式
    建造者模式
    原型模式
    单例模式
    Java8新特性——集合底层源码实现的改变
  • 原文地址:https://www.cnblogs.com/helloforworld/p/5655285.html
Copyright © 2011-2022 走看看