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;

  • 相关阅读:
    npm镜像切换
    vue组件样式覆盖问题-module
    实现微信小程序多文件同时上传,并且携带参数
    提交现有代码到gitee
    富文本框 字段存入数据库
    js动态添加 <select>标签disable属性
    validate验证,rules属性名为特殊属性名
    springboot themleaf ajax总结
    th:field,th:value
    直接在页面上显示当前年份
  • 原文地址:https://www.cnblogs.com/lyjbk/p/12834763.html
Copyright © 2011-2022 走看看