动多态发生的情况

动多态发生的情况:指针或者引用的完整对象调用虚函数

pb1->show();
pb2->show();
pd1->show(); 

分析以上产生静多态还是动多态?

#include<iostream>
using namespace std;
class Base
{
public:
	Base(int a) :ma(a)
	{
		cout << "Base::Base(int)" << endl;
	}
	~Base()
	{
		cout << "Base::~Base()" << endl;
	}
	virtual void show()
	{
		cout << "Base::show()" << endl;
		cout << "ma:" << ma << endl;
	}
protected:
	int ma;
};
class Derive :public Base
{
public:
	Derive(int b) :mb(b), Base(b)
	{
		cout << "Derive::Derive(int)" << endl;
	}
	~Derive()
	{
		cout << "Derive::~Derive()" << endl;
		cout << "ma:" << ma << endl;
		cout << "mb:" << mb << endl;
	}
	void show()
	{
		cout << "Derive::show()" << endl;
	}
private:
	int mb;
};
int main()
{
	Base b(10);
	Derive d(20);
	Base* pb1 = &b;
	pb1->show();
	Base* pb2 = &d;
	pb2->show();
	Derive* pd1 = &d;
	pd1->show();
}

基类和派生类中均无虚函数,则均为静多态

基类中无虚函数,派生类中有虚函数:分别为静多态、静多态(从指针所对应的基类Base中找show,看是不是虚函数,不满足,则为静多态)、动多态

基类中有虚函数,派生类中也有虚函数(从基类中继承过来的):三个调均产生动多态

    Base& rb1 = b;
	rb1.show();
	Base& rb2 = d;
	rb2.show();
	Derive& rd1 = d;
	rd1.show();

以上引用和前边指针同理。

猜你喜欢

转载自blog.csdn.net/Aspiration_1314/article/details/86545677