您的位置:首页 > 编程语言 > C语言/C++

c++快速简易入门教程_007虚函数与多态性、纯虚函数

2016-04-11 17:55 176 查看

1 虚函数与多态性

这节我们学习c++中的虚函数与多态性、和纯虚函数,先来看一个例子:

#include <iostream>

using namespace std;

class animal{

public :
void eat(){
cout << "animal eat" << endl;
}
void sleep(){
cout << "animal sleep" << endl;
}
void breathe(){
cout << "animal breathe" << endl;
}
};

class fish :public animal{

public:
void breathe(){
cout << "fish bubble" << endl;
}
};

void fn(animal* pAn){
pAn->breathe();
}

void main(){

animal* pAn;
fish fh;
pAn = &fh;
fn(pAn);

system("pause");
return;
}
运行结果:

animal breathe
请按任意键继续. . .
为什么会出现这样的结果呢?这是因为在将fish对象fh的地址赋给pAn时,c++编译器进行了类型转换,认为变量pAn保存就是animal对象的地址,这里我们分析一下fish类对象的内存模型如下图所示:



在我们构造fish类时,我们首先调用animal类的构造方法去构造,然后才调用fish自己的构造方法,当我们给fn()传递一个fish对象时,这个指针是指向上图的fish类的上半部分animal所占的空间的头部所以我们看到的是执行animal的breathe()方法。那么如何才能让执行fish的方法呢?其实很简单我们只要在基类animal的breathe()方法前面加一个virtual关键字,用virtual关键字申明的函数叫做虚函数,其实这样就实现了多态,多态用一句话概括就是:在基类的函数前加上virtual关键字,在派生类中重写该函数,运行时将会根据对象的实际类型来调用相应的函数。
多态程序:

#include <iostream>

using namespace std;

class animal{

public :
void eat(){
cout << "animal eat" << endl;
}
void sleep(){
cout << "animal sleep" << endl;
}
virtual void breathe(){
cout << "animal breathe" << endl;
}
};

class fish :public animal{

public:
void breathe(){
cout << "fish bubble" << endl;
}
};

void fn(animal* pAn){
pAn->breathe();
}

void main(){

animal* pAn;
fish fh;
pAn = &fh;
fn(pAn);

system("pause");
return;
}

运行结果:

fish bubble
请按任意键继续. . .

2 纯虚函数

我们将上面的breathe()函数申明为纯虚函数,如下所示:

class animal{

public :
void eat(){
cout << "animal eat" << endl;
}
void sleep(){
cout << "animal sleep" << endl;
}
virtual void breathe()=0;
}
};
这里我们需要特别注意纯虚函数,它让类先具有一个操作名称而没有操作对象,让派生类去实现具体的方法,凡是含有纯虚函数的类叫做抽象类,这种类不能被实例化只能被继承,即抽象类不能被申明对象,只是作为基类派生。我们需要特别注意c++的多态是由虚函数来实现的而不是纯虚函数,纯虚函数在我们设计基类时会有很大的好处。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: