zoukankan      html  css  js  c++  java
  • c++多态之动态绑定

    C++的函数调用默认不使用动态绑定。要触发动态绑定,必须满足两个条件:

    1. 只有指定为虚函数的成员函数才能进行动态绑定
    2. 必须通过基类类型的引用或指针进行函数调用

    因为每个派生类对象中都拥有基类部分,所以可以使用基类类型的指针或引用来引用派生类对象

    示例

    #include <iostream>
    #include <string>
    using namespace std;
    
    struct base
    {
        base(string str = "Base") : basename(str) {}
        virtual void print() { cout << basename << endl; }
        private:
            string basename;
    };
    struct derived : public base
    {
        derived(string str = "Derived") : derivedname(str) {}
        void print() { cout << derivedname << endl; }
        private:
            string  derivedname;
    };
    
    int main()
    {
        base b;
        derived d;
        cout << "b.print(), d.print()" << endl;
        b.print();
        d.print();
    
        base *pb = &b;
        base *pd = &d;
        cout << "pb->print(), pd->print()" << endl;
        pb->print();
        pd->print();
    
        base &yb = b;
        base &yd = d;
        cout << "yb.print(), yd.print()" << endl;
        yb.print();
        yd.print();
    }
    

    结果

    img

    分析

    可以看出基类类型的指针或引用来引用派生类对象时,调用的是重定义的虚函数。要想覆盖虚函数机制,调用基函数的版本,可以使用强制措施。例:

    代码

    #include <iostream>
    #include <string>
    using namespace std;
    
    struct base
    {
        base(string str = "Base") : basename(str) {}
        virtual void print() { cout << basename << endl; }
        private:
            string basename;
    };
    struct derived : public base
    {
        derived(string str = "Derived") : derivedname(str) {}
        void print() { cout << derivedname << endl; }
        private:
            string  derivedname;
    };
    
    int main()
    {
        base b;
        derived d;
        cout << "b.print(), d.print()" << endl;
        b.print();
        d.base::print();
    
        base *pb = &b;
        base *pd = &d;
        cout << "pb->print(), pd->print()" << endl;
        pb->print();
        pd->base::print();
    
        base &yb = b;
        base &yd = d;
        cout << "yb.print(), yd.print()" << endl;
        yb.print();
        yd.base::print();
    }
    

    结果

    img

    转自https://www.cnblogs.com/kaituorensheng/p/3509593.html

  • 相关阅读:
    构造函数和属性初始化
    C#3.0新增功能06 对象和集合初始值设定项
    C#动态操作DataTable(新增行、列、查询行、列等)
    快速排序
    HTML5原生拖放实例分析
    从web移动端布局到react native布局
    Chrome浏览器Network面板http请求时间分析
    CSS3之3D变换实例详解
    移动端行列布局
    SVG描边动画原理
  • 原文地址:https://www.cnblogs.com/Chlik/p/13555761.html
Copyright © 2011-2022 走看看