关于c++的多态

c++多态分为两种:

1.静态多态(静态绑定): 绑定发生在编译期.

如函数重载--------两个函数名称一样,参数类型或个数不完全相同,函数的返回类型可以不一样.

2.动态多态(动态绑定): 绑定发生在运行期.

        动多态则是通过继承、虚函数(virtual)、指针(应用)来实现.

例子1.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
class A
{
	public:
		virtual A* Create();
};
A* A::Create()
{
	printf("Parent Called\n");
	return NULL;
}
class B: public A
{
	public:
		virtual B* Create();
};
B* B::Create()
{
	printf("Child Called\n");
	return NULL;
}
int main()
{
	B b;
	A& a = b;
	a.Create();//输出  Child Called ------多态调用函数时和父子类中函数的返回类型没有多少关系.和函数名和参数(个数、类型)相关.
	return 0;
}


 例子2.

#include <stdio.h>
struct Point
{
	int x;
	int y;
	void DebugPrint()
	{
		printf("[x, y] = [%d, %d]\n", x, y);
	}
};
class A
{
	public:
		virtual Point* GetPoint();
		virtual void Init();
};
void A::Init()
{
	Point* point = GetPoint();
	point->DebugPrint();
}


Point* A::GetPoint()
{
	printf("Parent A.\n");
	return NULL;
}
class B: public A
{
	public:
		B(int x, int y);
		~B();
		Point* GetPoint();


	protected:
		Point point;
};
Point* B::GetPoint()
{
	printf("Child B.\n");
	return &point;
}
B::B(int x, int y)
{
	point.x = x;
	point.y = y;
}
B::~B()
{}


int main()
{
	B b(10, 9);
	A& a = b;
	a.Init();//里面调用的是B::GetPoint(),这也是一种多态的使用.
	return 0;
}

说明:

1.含有虚函数的类的对象的数据区的开始位置存放的是一个指向虚表的指针,当出现一个父类指针(或引用)指向子类对象,然后通过父类指针或是引用调用子类函数时回去查虚表中有没有被调用函数,如果有则调用(子类中的),没有则会调用父类的。

2.父类中的虚函数必须要实现,不能只有声明。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值