zoukankan      html  css  js  c++  java
  • 重写、重载、隐藏以及多态分析

    https://blog.csdn.net/jiangtaigong/article/details/83255471
    https://blog.csdn.net/alpha_love/article/details/75222175
    静态多态包括函数重载(通过不同的函数参数选择不同的函数)与函数模板(泛型定义template)
    运行时的多态需要满足三个条件:继承(子类继承了父类),重写(virtual),向上转型(父类指针指向子类对象)
    基类中是否出现virtual很关键,若出现,无论virtual是出现在私有区域还是共有区域,只要在基类中出现,就会创建出虚函数表,派生类即会继承这个虚函数表,但若没有实现向上转型,虽然还是会出现类似动态多态的情况,但是此时并不是动态多态,而是子类对父类成员进行了隐藏
    若基类中没有出现virtual,且子类继承了父类,同时又实现了与父类的同名函数,此时就会出现子类对父类成员函数的隐藏,即子类对象在调用与父类同名的方法时使用的是子类的方法,调用不到与父类同名的方法和属性,若需要调用父类的方法和属性,请通过child.parent::()来实现子类对父类中方法的使用
    注意virtual的位置,virtual可以修饰私有成员,但是一般不会这样去做,会造成混乱

    #include <iostream>
    using namespace std;
    
    class P {
    private:
    	virtual void showMeImpl();
    public:
    	void showMe();
    };
    void P::showMeImpl() {
    	cout << "here is the parent" << endl;
    }
    
    void P::showMe() {
    	showMeImpl();
    }
    
    class C : public P {
    private:
    	void showMeImpl();
    public:
    	void showMe();
    };
    
    void C::showMeImpl() {
    	cout << "here is the child" << endl;
    }
    
    void C::showMe() {
    	cout << "here is the childhhhhhhhhhhhhh" << endl;
    }
    int main() {
    	C c;
    	P& p = c;
    	p.showMe();
    	P* p2 = &c;
    	p2->showMe();
    }
    

    若virtual修饰的是showMeImpl,那么结果为
    here is the child
    here is the child
    若virtual修饰的是showMe,那么结果为
    here is the childhhhhhhhhhhhhh
    here is the childhhhhhhhhhhhhh

  • 相关阅读:
    libevent学习总结
    C#结构体的使用
    函数常用类
    C#函数的基础应用
    数组的应用:冒泡排序,折半查找及二维数组的应用
    作业
    复习break、continue、while、do-while的运用
    编程常用英语单词
    作业:for循环,迭代法和穷举法
    循环语句
  • 原文地址:https://www.cnblogs.com/sunshine-free/p/13817500.html
Copyright © 2011-2022 走看看