C++编程练习:多态实验——设计一个基类Shapes,Shapes类公有派生产生矩形类Rectangle和圆类Circle

例、设计一个基类Shapes,包含成员函数display()并声明为纯虚函数。Shapes类公有派生产生矩形类Rectangle和圆类Circle,分别定义display()函数实现其主要几何元素的显示。使用抽象类Shapes类型的指针(或引用),当它指向(或引用)某个派生类的对象时,就可以通过它访问该对象的虚成员函数display()实现动态多态性。

代码如下:

头文件:

//头文件
#include <iostream>
#define PI 3.141265
using namespace std;
class Shapes
{
public:
	virtual void display() = 0;		//成员函数dispaly()声明为纯虚函数
};

class Rectangle : virtual public Shapes
{
protected:
	float x, y;
public:
	float length;
	float width;
	Rectangle()
	{
	}
	Rectangle(float a, float b)
	{
		x = a;
		y = b;
	}
	virtual float getRectangle()
	{
		return (x * y);
	}
	virtual void display()
	{
		cout << "矩形的长为:" << x << endl;
		cout << "矩形的宽为:" << y << endl;
		cout << "矩形的面积为:" << getRectangle() << endl;
	}
};

class Circle : virtual public Shapes
{
protected:
	int r;
public:
	Circle()
	{
	}
	Circle(float R)
	{
		r = R;
	}
	virtual float getCircle()
	{
		return PI * r * r;
	}
	virtual void display()
	{
		cout << "圆的半径为:" << r << endl;
		cout << "圆的面积为:" << getCircle() << endl;
	}
};

主函数:

//主函数
#include <iostream>
#include "头文件.h"
#define PI 3.141265
using namespace std;
int main()
{
	Shapes* p;
	double a = 0, b = 0, r = 0;
	cout << "请分别输入矩形的长和宽:" << endl;
	cin >> a >> b;
	Rectangle A(a, b);
	p = &A;
	p->display();
	cout << "" << endl;
	cout << "请输入圆的半径:" << endl;
	cin >> r;
	Circle B(r);
	p = &B;
	p->display();
	system("pause");
	return 0;
}

测试功能:

代码测试成功!

 

以上就是本次C++的全部内容,感谢您的阅读和支持,篇幅较长,若有表述或者代码中的不当之处,望指出!您的指出和建议能给作者带来很大的动力!!!

  • 4
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晚风(●•σ )

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值