类和对象 多态——定义几何图形抽象类Shape

Posted 猛男Banana君

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了类和对象 多态——定义几何图形抽象类Shape相关的知识,希望对你有一定的参考价值。

题目:
在这里插入图片描述

#include<iostream>
#include<iomanip> 
using namespace std;
#define PI 3.1415926

class Shape                    //抽象类,包含两个纯虚函数
{
public:
	virtual float Area() = 0;
	virtual void SetData(float, float = 0) = 0;
};

class Triangle :public Shape
{
	float w, h;
public:
	Triangle(float w1 = 0, float h1 = 0) :w(w1), h(h1) {}
	float Area() { return w * h / 2; }
	void SetData(float w1, float h1 = 0) { w = w1, h = h1; }
};

class Rectangle :public Shape
{
	float w, h;
public:
	Rectangle(float w1 = 0, float h1 = 0) :w(w1), h(h1) {}
	float Area() { return w * h; }
	void SetData(float w1, float h1 = 0) { w = w1, h = h1; }
};

class Square :public Shape
{
	float s;
public:
	Square(float s1 = 0) :s(s1) {}
	float Area() { return s * s; }
	void SetData(float, float s1 = 0) { s = s1; }
};

class Circle :public Shape
{
	float r;
public:
	Circle(float r1 = 0) :r(r1) {}
	float Area() { return PI * r * r; }
	void SetData(float, float r1 = 0) { r = r1; }
};

float CalcArea(Shape* p)
{
	return p->Area();
}

int main()
{
	Triangle T;
	T.SetData(2, 2);
	Rectangle R;
	R.SetData(4, 5);
	Square S;
	S.SetData(0, 2);
	Circle C;
	C.SetData(0, 2);

	float sum = 0;         //总面积 
	sum += CalcArea(&T) + CalcArea(&R) + CalcArea(&S) + CalcArea(&C);
	cout << "三角形面积为:" << CalcArea(&T) << endl;
	cout << "矩形面积为:" << CalcArea(&R) << endl;
	cout << "正方形面积为:" << CalcArea(&S) << endl;
	cout << "圆面积为:" << fixed << setprecision(3) << CalcArea(&C) << endl;
	cout << "总面积为:" << sum << endl;

	return 0;
}

以上是关于类和对象 多态——定义几何图形抽象类Shape的主要内容,如果未能解决你的问题,请参考以下文章

第52课 C++中的抽象类和接口

JAVA 作业 实验名称:接口,继承与多态

定义抽象类Shape,抽象方法为showArea(),求出面积并显示,定义矩形类Rectangle,正方形类Square,圆类 Circle,根据各自的属性,用showArea方法求出各自的面积,在m

自定义异常基于类和对象多态继承抽象接口异常的汽车选择查询

JAVA面向对象的多态性及抽象类和接口

Java 抽象类和接口(部分)