码迷,mamicode.com
首页 > 其他好文 > 详细

抽象类中定义纯虚函数

时间:2015-07-31 13:06:43      阅读:119      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!