您的位置:首页 > 其它

面向对象的多态性(2)

2015-09-01 18:28 239 查看
1、虚函数

在c++中,可以调用虚函数来实现运行时的多态性,,这样可以进行函数的重载

虚函数的定义是在基类中进行的,,当吧基类中的某一个成员函数定义成虚函数之后,就可以在派生类中重新定义,

在派生类重新定义的时候,函数的原型包含函数参数,函数名,参数的个数和类型,以及参数的顺序都必须和基类中的函数一样

虚函数的定义形式:

virtual <函数类型》《函数名》(参数表)

{

函数体

}

该函数定义一个虚函数,在派生类总继承基类,对虚函数重新的定义

<span style="font-size:18px;">#include<iostream>
using namespace std;
class animal
{
public:
	void sleep(){
		cout << "animal is sleeping" << endl;

	}
	virtual void breath(){
		cout << "aniaml is breathing" << endl;
	}
};
class fish :public animal
{
public:
	void breath(){
		cout << "fish is breathing" << endl;
	}
};

int main()
{
	animal an;
	an.breath();

	fish fh;
	fh.breath();

	animal *ann = &fh;
	ann->breath();
	system("pause");
		return 0;

}</span>


在基类函数中间virtual关键字 后,当基类对象的指针指向fish类的对象时,会调用fish类中的函数,得到预期的效果

当基类的成员函数breath()函数定义为虚函数时,编译器为每个包含虚函数的类创建一个虚表

类aniaml的虚表: &animal::breath()---------------------->animal::breath()

类fish的虚表:&fish::reath()-------------------------------->fish::brath()

当使用fish类的fh对象狗仔完后,,其内部的虚表指针按初始化指向fish类的虚表,

当进行类型转换后,调用ann-》breath()函数,由于ann实际指向的是fish对象,该对象内部的虚表指针指向的是fishle类的

虚表,最终调用fish类的breath()函数

在调用虚函数注意:

1、虚函数只能定义在基类中

2、重载的函数,要求函数名、返回类型、参数个数、参数类型和参数顺序必须和基类中的函数一样

3、在用基类对象访问重载函数时,需用指针进行调用

2、多级继承和虚函数

多级继承可以看作多个继承的组合,多级继承的虚函数和单继承的而虚函数相同,一个虚函数无论被继承多少次,仍然保持虚函数的特性,与继承次数无关

例子:

#include<iostream>
using namespace std;
class base
{
public:
	virtual ~base(){};
	
	virtual void func()
	{
		cout << "base output" << endl;
	}
};
class derive1 :public base
{
public:
	void func()
	{
		cout << "derive1 output" << endl;
	}
};
class derive2 :public derive1
{
	void func()
	{
		cout << "derive2 output" << endl;
	}
};

void test(base &b)
{
	b.func();
}
int main()
{
	base bob;
	derive1 dob1;
	derive2 dob2;
	test(bob);
	test(dob1);
	test(dob2);
	system("pause");
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: