一、抽象类
1、抽象类不能实例化;
2、抽象类只作为基类被继承;
3、可以定义抽象类的指针或引用;
4、含有纯虚函数的类即为抽象类;
二、纯虚函数
1、纯虚函数定义:virtual 返回类型 函数名(参数表)= 0
2、纯虚函数具体实现只能在派生类中完成;
#include<iostream>
using namespace std;
#define PI 3.14
class Shape{
public:
virtual double Area()=0;
};
class Rectangle:public Shape{
private:
int x,y;
int w,h;
public:
Rectangle(int x, int y, int w, int h){
this->x=x;
this->y=y;
this->w=w;
this->h=h;
}
double Area(){
return w*h;
}
};
class Circle:public Shape{
private:
int x,y;
int r;
public:
Circle(int x, int y, int r){
this->x=x;
this->y=y;
this->r=r;
}
double Area(){
return PI*r*r;
}
};
int main(){
Rectangle r1(2,2,4,2);
Circle c1(2,2,1);
Shape *p1=&r1;
Shape &p2=c1;
cout<<"矩形面积="<<p1->Area()<<endl;
cout<<"圆的面积="<<p2.Area()<<endl;
return 0;
}
运行结果:
矩形面积=8
圆的面积=3.14