利用虚基类继承:实现从shape到圆,三角形,矩形

  • Post author:
  • Post category:其他


1.纯虚函数语法:virtual returntype func_name(xxx) = 0;

2.继承自 虚基类之后 ,需要 如果不添加新的 接口,那么需要写两种函数:

(1)派生类的构造函数

(2)重写虚函数(或者纯虚函数)

#include<iostream>
#include<string>
#include<cmath>
using namespace std;
//定义PI为3.14
#define PI 3.14

//虚基类-shape
class Shape
{
public:
	virtual double area() = 0;
	virtual double perimeter() = 0;
	virtual void scale(double factor) = 0;

};
//1.circle圆形
class Circle:public Shape
{
private:
	double radius;
public:
	//构造函数
	Circle(double r) :radius(r) {};

	//重写纯虚函数
	double area()
	{
		return PI * radius*radius;
	}
	double perimeter()
	{
		return 2 * PI*radius;
	}
	void scale(double factor)
	{
		radius *= factor;
	}

};

//2.三角形
class Triangle :public Shape
{
private:
	double a, b, c;  //利用海伦公式求面积
public:
	//构造函数
	Triangle(double a_, double b_, double c_) :a(a_), b(b_), c(c_) {};
	//重写纯虚函数
	double area()
	{
		//海伦公式
		double p = (a + b + c) / 2;
		return sqrt(p*(p - a)*(p - b)*(p - c));
	}
	double perimeter()
	{
		return a + b + c;
	}
	void scale(double factor)
	{
		a *= factor;
		b *= factor;
		c *= factor;
	}
};
//3.矩形
class Rectangle:public Shape
{
private:
	double width, height;
public:
	//构造函数
	Rectangle(double wid, double hei) :width(wid), height(hei) {};
	//重写纯虚函数
	double area() {
		return width * height;
	}
	double perimeter()
	{
		return 2 * (width + height);
	}
	void scale(double factor)
	{
		width *= factor;
		height *= factor;
	}
};

int main()
{
	//测试:
	Circle circle(1);
	Triangle triangle(1, 1, 1);
	Rectangle  rectangle(1, 1);
	cout << "圆的面积是 : " << circle.area() << endl << "圆的周长是 : " << circle.perimeter() << endl;
	cout << "三角形的面积是 : " << triangle.area() << endl << "三角形的周长是 : " << triangle.perimeter() << endl;
	cout << "矩形的面积是 : " << rectangle.area() << endl << "矩形的周长是 : " << rectangle.perimeter() << endl;

	return 0;
}



版权声明:本文为xiao_ZHEDA原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。