Polymorphism

Polymorphism happens as program is running , when the type of the parameter passed in is different from it's definition(usually defined as a parent class  pass a subclass), and we will call the parameter's method in this method.

there should be a rule whether to call the parent's method or call the subclass' method.

for static binding, it depends on the type of the definition;

for dynamic binding, it depends on the type of the object we passed in.

attention:

in order to realize dynamic binding, besides the virtual key words, we should define the function's parameter as &.

#include "stdafx.h"
#include <iostream>
using namespace std;

class CParent
{
public:
	virtual void name(){cout<<"parent";}
};
class CSon:public CParent
{
public:
	virtual void name(){cout<<"son";}
};
class CDaughter:public CParent
{
public:
	void name(){cout<<"daughter";}
};
void callName(CParent &person)
{
	person.name();
}
int _tmain(int argc, _TCHAR* argv[])
{
	CSon son1;
	callName(son1);
	int i;
	cin>>i;
	return 0;
}

the out put is parent;


this one's  output is son

#include "stdafx.h"
#include <iostream>
using namespace std;

class CParent
{
public:
	virtual void sayname(){cout<<"parent";}
	 void name(){sayname();};
};
class CSon:public CParent
{
public:
	virtual void sayname(){cout<<"son";}
	//virtual void name(){sayname();}
};
class CDaughter:public CParent
{
public:
	void name(){cout<<"daughter";}
};
void callName(CParent &person)
{
	person.name();
}
/*void callName(CSon &son)
{
	son.name();
}*/
int _tmain(int argc, _TCHAR* argv[])
{
	CSon son1;
	//CParent parent1;
	callName(son1);
	int i;
	cin>>i;
	return 0;
}


当父类和子类都有相同函数定义的时候,如何确定到底调用的是父类的函数还是调用的子类的函数。

1. 对象式

func()

{

CClass object;

object.method();

}

不管method是否有virtual,都是先严格按照object的对象类型。当object没有该方法,再去调用父类。

2.指针式

Parent p;

Son s1

Son *pSon = &p;

p->func() // parent's function

Son*pSon2 = &s1;

p->func()// son's funcion

严格按照指针实际指向的对象的类型,先去调用该类型的方法。如果没有再沿着父类向上找。

2.参数式(对象不是在函数中定义,而是从参数中传入)

func(Parent &object)

{

object.method()

}

 如果method有virtual,并且定义参数为引用或者指针,则按照实际运行中传入对象的类型

否则按照func声明中参数的类型。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值