纯虚函数
虚函数是实现多态性的前提需要在基类中定义共同的接口
接口要定义为虚函数
如果基类的接口没办法实现(如形状类Shape)
解决办法
将这些接口定义为纯虚函数
定义纯虚函数:
class 类名{
virtual 返回值类型 函数名(参数表)=0;
};
纯虚函数不需要实现
#include <iostream>
#include <vector>
using namespace std;
class Shape
{
public:
virtual void Draw() = 0;//纯虚函数
/*void Draw()//
{
cout << "Shape ..." << endl;
}
*/
};
class Circle : public Shape
{
public:
void Draw()//派生类中必须实现基类中的纯虚函数,否则它仍将被看作是一个抽象类
{
cout << "Circle::Draw() ..." << endl;
}
};
class Square : public Shape
{
public:
void Draw()
{
cout << "Square::Draw() ..." << endl;
}
};
void DrawAllShapes(const vector<Shape*>& v)
{
vector<Shape*>::const_iterator it;
for (it = v.begin(); it != v.end(); ++it)
{
(*it)->Draw();//基类指针,基类的Draw是虚函数,所以其指向派生类的虚函数
}
}
int main()
{
//Shape s; //Error,不能实例化抽象类
vector<Shape*>v;
Shape* ps;
ps = new Circle;
v.push_back(ps);
ps = new Square;
v.push_back(ps);
DrawAllShapes(v);
return 0;
}
#include <iostream>
using namespace std;
//对于一个没有任何接口的类,如果想要将它定义成抽象类,只能将虚析构函数声明为纯虚的
//通常情况下在基类中纯虚函数不需要实现
//例外是纯虚析构函数要给出实现。(给出一个空的实现)
class Base
{
public:
virtual ~Base() = 0
{
}
};
class Drived : public Base
{
};
int main(void)
{
Drived d;
return 0;
}