整理摘自https://blog.****.net/ithomer/article/details/6031329
1. 申明格式
class CShape
{
public:
virtual void Show()=;
};
在普通的虚函数后面加上"=0"这样就声明了一个pure virtual function.
2. 何时使用纯虚函数?
3. 举例说明
(1)不可实例化含有虚函数的基类
我们来举个例子,我们先定义一个形状的类(Cshape),但凡是形状我们都要求其能显示自己。所以我们定义了一个类如下:
class CShape
{
virtual void Show(){};
};
但没有CShape这种形状,因此我们不想让CShape这个类被实例化,我们首先想到的是将Show函数的定义(实现)部分删除如下:
class CShape
{
virtual void Show();
};
class CShape
{
public:
virtual void Show()=;
};
当实例化CShape cs 后,会报错:
error: cannot declare variable ‘cs’ to be of abstract type ‘CShape’
CShape cs;
^
note: because the following virtual functions are pure within ‘CShape’:
class CShape
^
note: virtual void CShape::Show()
virtual void Show()= 0;
^
(2)派生类中堆基类中虚函数的实现
class CShape
{
public:
virtual void Show()= ;
}; class CPoint2D: public CShape
{
public: void Msg()
{
printf("CPoint2D.Msg() is invoked.\n");
}
/*
void Show()
{
printf("Show() from CPoint2D.\n");
}
*/
};
当实例化 CPoint2D p2d时,报错
error: cannot declare variable ‘p2d’ to be of abstract type ‘CPoint2D’
CPoint2D p2d;
^
note: because the following virtual functions are pure within ‘CPoint2D’:
class CPoint2D: public CShape
^
note: virtual void CShape::Show()
virtual void Show()= 0;
^
我们预防了在派生类中忘记实现基类方法。如果不在派生类的中实现在Show方法,编译都不会通过。
以下为完整代码:
#include <iostream>
#include <cstdio>
using namespace std; class CShape
{
public:
virtual void Show()= ;
}; class CPoint2D: public CShape
{
public: void Msg()
{
printf("CPoint2D.Msg() is invoked.\n");
} void Show()
{
printf("Show() from CPoint2D.\n");
}
}; int main()
{
CPoint2D p2d;
p2d.Msg();
CPoint2D *pShape = &p2d;
pShape -> Show();
return ;
} /* Output:
CPoint2D.Msg() is invoked.
Show() from CPoint2D.
*/