C++的继承和派生(五)纯虚函数和抽象类

在上一篇提到了虚函数,可以发现,虚函数并没有实现相应的功能,只是提供了类似于接口的功能。所以在C++中可以将虚函数声明为纯虚函数,其语法格式为:

virtual 返回值类型 函数名 (函数参数)=0

说明:
1、纯虚函数没有函数体,只有函数声明,在虚函数声明的结尾加上 “=0”,表明此函数是纯虚函数
2、包含纯虚函数的类称为抽象类,抽象类无法创建对象
3、抽象类也可以包含非纯虚函数、成员变量
4、如果父类是抽象类,子类没有完全重写纯虚函数,那么这个子类依然是纯虚函数
5、只有类中的虚函数才可以被定义为虚函数,普通成员函数和顶层函数不可以均不能声明为纯虚函数

下面举个纯虚函数的例子

计算不同形状的图形的面积---------------------------------------------------------------------

class Shape{
public:
	virtual float getAre()=0;
	virtual void show()=0;
	virtual ~Shape(){}
};

class Retcangle:public Shape{
private:
	int m_lenth,m_width;
public:
	Retcangle(int length,int width) : m_lenth(length) ,m_width(width){}
	float getAre(){
		return m_lenth*m_width;
	}
	void show(){
		printf("Rectangle-Area=%f\n",getAre());
	}
};

class Triangle:public Shape{
private:
	int m_base,m_height;
public:
	Triangle(int base,int height) : m_base(base) ,m_height(height){}
	float getAre(){
		return m_base*m_height/2;
	}
	void show(){
		printf("Triangle-Area=%f\n",getAre());
	}
};

class Circle:public Shape{
private:
	int m_radius;
public:
	Circle(int radius) : m_radius(radius){}
	float getAre(){
		return m_radius*m_radius*M_PI;
	}
	void show(){
		printf("Circle-Area=%f\n",getAre());
	}
};

void Display(Shape* p) {
	p->getAre();
	p->show();
}

int main(){
	
	Display(new Retcangle(1,1));
	Display(new Triangle(2,2));
	Display(new Circle(1));

	return 0;
}

运行结果

Rectangle-Area=1.000000
Triangle-Area=2.000000
Circle-Area=3.141593

猜你喜欢

转载自blog.csdn.net/qq_47329614/article/details/106961846