首页 > 其他 > 详细

抽象类中定义纯虚函数

时间:2015-07-31 13:06:34      阅读:179      评论:0      收藏:0      [点我收藏+]

首先看一段代码:

class Instrument
{
public:
virtual	void play()const=0//非法的定义在抽象类中定义纯虚函数
	{
		cout<<"Instrument Play\n";
	}
};

class Wind:public Instrument
{
	void play( )const
	{
		cout<<"Wind Play\n";
	}
};

void main()
{
	Wind s;
	Instrument &p = s;
	p.play();
}

以下是纯虚函数在抽象类中的定义:

#include <iostream>
#include <string>
using namespace std;

class Instrument
{
public:
	virtual void play()const =0;//纯虚函数    这个抽象类的虚函数指针是空的
                              //不可以内联实现纯虚函数,但是可以在类外部实现
};
//在基类作为抽象类的视乎为其的纯虚函数提供定义是可以的,这样可以使一些公共代码可以在一些或者所有的派生类中都能调用
void Instrument::play()const
{
	cout<<"Instrument play()\n";
}
/*以下方式也可以
inline void Instrument::play()const
{
	cout<<"Instrument play()\n";
}*/


class Wind:public Instrument
{
	void play()const
	{
		Instrument::play();
		cout<<"Wind Play()\n";
	}
};

void main()
{
	Wind s;
	Instrument &p = s;
	p.play();
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

抽象类中定义纯虚函数

原文:http://blog.csdn.net/kai8wei/article/details/47167085

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!