首页 > 技术文章 > 重写、重载、隐藏以及多态分析

sunshine-free 2020-10-14 21:30 原文

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

推荐阅读