4类多态


    在软考学习的时候,才发现多态不只唯独我认识的那么一两种,非常多用过的形式原来它们也是多态呀。


    首先来看下大图:


   

      



         接下来本文将一一举例这些多态,并在末尾做个小对照。


一。简单介绍几种多态


    1。泛型


                这个听起来比較高大上,可是大家都用过。比如:


 

        机房收费系统——组合查询中,为了尽可能抽出同样部分。使用T取代。还有转换成list的时候,在定义中指定List of T,使用时:


	 mylist = Entity.EntityConverter.convertToList(Of Entity.StuBaseInfo)(dt)

     2,模板


          这个在C++中见的非常多,别的语言中还没实用过,所以就用C++举例了:

    

template <typename T>
T max(const T& lsh, const T& rhs) 
{
return (lsh > rhs) ? lsh : rhs;
}
//返回两个随意类型对象的最大值(对象),前提是该类型可以使用>
//运算符进行比較,而且返回值是bool类型。

//使用: int a = 3; int b = 4; cout << max(a, b) << endl; float c = 2.4; float d = 1.2; cout << max(c, d) << endl; //输出结果为: //4 //2.4



           相同是使用时指定T,可是泛型比模板多了对參数的检查功能。

  

    3,重写


           面向对象中,最常见的就是一个子类继承一个父类,然后重写它的方法了


          比如:一个类继承一个窗口,然后重写它button的点击事件:

 

        


           


    4,重载


            适用于一个功能有多个參数的情况:

        

           

	#include<iostream>
	#include<cstring>
	using namespace std;
	
	int myMax(int x,int y);	//比較两个整数
	char myMax(char first,char second);	//比較两个字符
	double myMax(double u,double v);  //比較两个小数
	char * myMax(char * frist,char * second);   //比較两个字符串
	
	int main()  //主函数
	{
		cout<<"in 3 and 5,the max number is "<<myMax(3,5)<<endl;  //调用比較整数的函数
		cout<<"in c and t the max char is:"<<myMax('c','t')<<endl;   //调用比較字符的函数
		cout<<"in 3.1 and -5.3,the max double number is:"<<myMax(3.1,-5.3)<<endl;  //调用比較浮点数的函数
		cout<<"in what and where the max string is:"<<myMax("what","where")<<endl;  //调用比較字符的函数
	
	}
	
	
	//以下为函数体
	
	int myMax(int x,int y)  //比較两个整数
	{
		if(x>y) return x;
		else return y;
	}
	
	char myMax(char first,char second)  //比較两个字符
	{
		if(first>second) return first;
		else return second;
	
	}
	
	double myMax(double u,double v)  //比較两个小数
	{
		if(u>v) return u;
		else return v;
	}
	
	char * myMax(char * first,char * second)   //比較两个字符串
	{
		if(strcmp(first,second)>0) return first;
		else return second;
	
	}


     

   5。父类引用指向子类对象


             超级熟悉了吧,设计模式中用的最多的,自我感觉不仅是用的最多的,也是最好用的,举个样例:


  

<span style="font-size:18px;">        Animal a=new Dog();  </span>

            


    二,小结


    





       


         





     


   

posted @ 2017-04-15 19:37  zhchoutai  阅读(519)  评论(0编辑  收藏  举报