设计模式基础1——多态练习

        面向对象有三个基本特征:封装、多态、继承。具体如下图:



From:http://www.cnitblog.com/Lily/archive/2006/02/23/6860.aspx


        学好这三个特征是掌握设计模式的前提。接下来以一个简单的C++程序为例,练习一下多态中的虚函数:

/*******************************************************/
//名称:C++多态练习(Animal)
//时间:2014年4月4日11:19:07
//作者:Lynch
/*******************************************************/

#pragma once
#include<iostream>
#include"Animal.h"
#include"Dog.h"
#include"Cat.h"
#include"Cow.h"
using namespace std;

int main()
{
	string name="Lin";
	int shoutNum=3;

	Animal *cat=new Cat();
	cat->setName(name);
	cat->setShoutNum(shoutNum);
	cout<<cat->Shout()<<endl;

	Animal *dog=new Dog();
	dog->setName(name);
	dog->setShoutNum(shoutNum);
	cout<<dog->Shout()<<endl;

	Animal *cow=new Cow();
	cow->setName(name);
	cow->setShoutNum(shoutNum);
	cout<<cow->Shout()<<endl;

	return 0;
}

#pragma once
#include<string>
using namespace std;

class Animal
{
public:
	virtual string Shout()=0;	//纯虚函数,该类不能实例化
	void setName(string name)
	{
		this->name=name;
	}
	void setShoutNum(int num)
	{
		this->shoutNum=num;
	}
protected:
	string name;
	int shoutNum;
};

#pragma once
#include "Animal.h"

class Cat :
	public Animal
{
public:

	virtual string Shout()
	{
		string str="My name is "+name+".";
		for(int i=0;i<shoutNum;i++)
		{
			str+=" MiaoMaio!";
		}
		return str;
	}
};

#pragma once
#include "Animal.h"

class Cow :
	public Animal
{
public:

	virtual string Shout()
	{
		string str="My name is "+name+".";
		for(int i=0;i<shoutNum;i++)
		{
			str+=" MangMang!";
		}
		return str;
	}
};

#pragma once
#include "Animal.h"

class Dog :
	public Animal
{
public:

	virtual string Shout()
	{
		string str="My name is "+name+".";
		for(int i=0;i<shoutNum;i++)
		{
			str+=" WangWang!";
		}
		return str;
	}
};

代码效果图:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章