C++ 实验八 虚函数和抽象类

前言

🎬本文章是 【C++笔记】 专栏的文章,主要是C++黑马的笔记、自己的实验与课设
🔗C++笔记 传送门

一、要求

编写一个程序计算三角形、正方形、圆的面积,要求抽象出一个基类 CBase ,在抽象类中设计两个纯虚函数,分别用来求面积和周长

二、分析

由要求分析可知,在Cbase类中声明纯虚函数,之后在Triangle类、Cube类、Circle类分别对两个函数重写,在main函数中通过指针调用

在这里插入图片描述

三、代码

💻提示:所有实验源码已在github整理

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

class CBase
{
public:
	virtual void area() = 0;
	virtual void circum() = 0;
};

class Triangle :public CBase
{
public:
	Triangle(double d, double h, double a, double b, double c)
	{
		this->d = d;
		this->h = h;
		this->a = a;
		this->b = b;
		this->c = c;
	}
	void area()
	{
		cout << "三角形的面积为" << d * h/2 << endl;
	}
	void circum()
	{
		cout << "三角形的周长为" << a + b + c << endl;
	}
private:
	double d;
	double h;
	double a;//定义三条边a,b,c
	double b;
	double c;
};

class Cube :public CBase
{
public:
	Cube(double c)
	{
		this->c = c;
	}
	void area()
	{
		cout << "长方形的面积为" << c * c << endl;
	}
	void circum()
	{
		cout << "长方形的周长为" << 4 * c << endl;
	}
private:
	double c;
};

class Circle :public CBase
{
public:
	Circle(double r)
	{
		this->r = r;
	}
	void area()
	{
		cout << "圆的面积为" << PI * r*r << endl;
	}
	void circum()
	{
		cout << "圆的周长为" << 2 * PI*r << endl;
	}
private:
	double r;
};
int main()
{
	CBase * t = new Triangle(3, 4, 3, 4, 5);
	t->area();
	t->circum();
	delete t;

	CBase * c = new Cube(1);
	c->area();
	c->circum();
	delete c;

	CBase * cir = new Circle(1);
	cir->area();
	cir->circum();
	delete cir;

	system("pause");
	return 0;
}

四、 结果

C++实验16

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值