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

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++的多态是由虚函数来实现的而不是纯虚函数,纯虚函数在我们设计基类时会有很大的好处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DaveBobo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值