zoukankan      html  css  js  c++  java
  • 用派生类对象初始化父类对象的同时遇上函数重载:多态的产生原因

    条件:

    (1)派生类含有基类的重写函数;

    (2)基类对象有派生类对象初始化(指针,引用,赋值);

    结果:

        基类对象调用重写函数时只调用基类函数

    结论:

       如何让编译器知道基类对象的真正类型,从而调用对应类型的成员,由此产生了多态的需求 , 即在重写函数前加virtual.

    #include <iostream>
    using namespace std;
    
    
    class Parent
    {
    public:
        Parent(int A)
        {
            this->a = A;
        }
         void print()
        {
            cout << "a=" << a<<endl;
        }
    private:
        int a;
    };
    
    class Child :public Parent
    {
    public:
        Child(int B) :Parent(10)
        {
            this->b = B;
        }
        void print()
        {
            cout << "b=" << b << endl;
        }
    private:
        int b;
    };
    
    int main()
    {
        Parent *p2 = NULL;
        Child ch(50);
        p2 = &ch;//用父类指针指向子类对象
        p2->print();
    
        Parent &p3 = ch;//用子类对象初始化父类引用
        p3.print();
    }

    输出结果均为:a=10;a=10;

    用virtual 修饰print()函数后:

    #include <iostream>
    using namespace std;
    
    
    class Parent
    {
    public:
        Parent(int A)
        {
            this->a = A;
        }
        virtual  void print()
        {
            cout << "a=" << a<<endl;
        }
    private:
        int a;
    };
    
    class Child :public Parent
    {
    public:
        Child(int B) :Parent(10)
        {
            this->b = B;
        }
        void print()
        {
            cout << "b=" << b << endl;
        }
    private:
        int b;
    };
    
    int main()
    {
        Parent *p2 = NULL;
        Child ch(50);
        p2 = &ch;
        p2->print();
    
        Parent &p3 = ch;
        p3.print();
        
    }

    输出结果均为:b=50;b=50;

  • 相关阅读:
    linux 下安装mongodb
    python 多线程, 多进程, 协程
    5.rabbitmq 主题
    4.rabbitmq 路由
    e.target与e.currentTarget对比
    使用ffmpeg下载m3u8流媒体
    本机添加多个git仓库账号
    IE hack 条件语句
    IE8 兼容 getElementsByClassName
    IE 下 log 调试的一点不同
  • 原文地址:https://www.cnblogs.com/lyjbk/p/12834763.html
Copyright © 2011-2022 走看看