小言_互联网的博客

动态多态

510人阅读  评论(0)
#include <iostream>
using namespace std;

class CWater
{
public:
	virtual void Show()   //  虚函数完成了 通过父类的指针 调用子类的函数 
	{
		cout << "CWater::Show" << endl;
	}
};


class CBeer : public CWater
{
public:
	void Show()
	{
		cout << "CBeer::Show" << endl;
	}
};

class CMilk : public CWater
{
public:
	void Show()
	{
		cout << "CMilk::Show" << endl;
	}
};


class CCoffee : public CWater
{
public:
	void Show()
	{
		cout << "CCoffee::Show" << endl;
	}
};

class CCoco :public CWater
{
public:
	void Show()
	{
		cout << "CCoco::Show" << endl;
	}
};


void Bottle(CWater* p)
{
	p->Show();
}



int main()
{
	CBeer* beer = new CBeer;
	CMilk* milk = new CMilk;
	CCoffee* coffee = new CCoffee;
	CCoco* coco = new CCoco;

	Bottle(beer);
	Bottle(milk);
	Bottle(coffee);
	Bottle(coco);

	system("pause");
	return 0;
}

转载:https://blog.csdn.net/weixin_44656803/article/details/101455944
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场