栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

文章目录
    • 前言
    • 一、要求
    • 二、分析
    • 三、代码
    • 四、 结果

前言

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

一、要求

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

二、分析

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

三、代码

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

#include
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;
}
四、 结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/935492.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号