文章目录
纯虚函数
- 如果一个虚函数仅表达抽象的行为,没有具体的功能,即只有声明没有定义,这样的虚函数被称为纯虚函数或抽象方法
cpp
class 类名 {
public:
virtual 返回类型 函数名 (形参表) = 0;
};
- 假设有图形类Figure, 设计计算面积的成员函数area()
- Figure只是一个纯抽象意义上得概念,不存在计算面积或体积的具体方法,所以只能将成员函数area()设计为纯虚函数
cpp
#include <iostream>
using namespace std;
class Figure{
protected:
double x, y;
public:
void set(double i, double j){
x = i;
y = j;
}
virtual void area()=0;
};
抽象类
- 如果类中包含了纯虚函数,那么这个类就是抽象类
- 抽象类只能最为其它类的基类,不能用来建立对象
- 如果类中的所有成员函数都是纯虚函数则可以称为纯抽象类
cpp
#include <iostream>
using namespace std;
class Shape{
public:
virtual void draw(void) = 0;
};
class Rect:public Shape{
public:
void draw(void){
cout << "draw Rect" << endl;
}
};
class Circle: public Shape{
public:
void draw(void){
cout << "draw Circle" << endl;
}
};
class Ellipse: public Shape{
public:
void draw(void){
cout << "draw Ellipse" << endl;
}
};
int main(void){
/*
Ellipse e;
e.draw();
e.Shape::draw();
*/
//Shape s1; //error
Shape *buf[128] = {0};
buf[0] = new Rect;
buf[1] = new Circle;
buf[2] = new Ellipse;
for(int i=0; buf[i] != NULL; i++){
buf[i]->draw();
}
return 0;
}