設計模式基礎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;
	}
};

代碼效果圖:



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