C++中定义一个图形基类,然后派生正方形、矩形等求面积和周长

定义类的头文件

Shape.h

#ifndef __SHAPE_H
#define __SHAPE_H

#include <iostream>
using namespace std;

class Shape
{
public:
	Shape();
	~Shape();
	virtual float area() = 0;
	virtual float perimeter() = 0;
};

class Square :public Shape
{
private:
	float width;
public:
	Square();
	Square(float b);
	~Square();
	float area();
	float perimeter();
	void setWidth(float b);
	void print();
};

class Rect : public Shape
{
public:
	Rect();
	Rect(float x, float y);
	~Rect();
	float area();
	float perimeter();
	void setWidth(float x, float y);
	void print();

private:
	float width;
	float height;
};

#endif // !__SHAPE_H

相关函数的定义以及使用

Shape.cpp

#include "Shape.h"

Shape::Shape()
{
	cout << "基类构造函数" << endl;
}

Shape::~Shape()
{
	cout << "基类析构函数" << endl;
}

Square::Square()
{
	width = 0;
}

Square::Square(float b)
{
	width = b;
}

Square::~Square(void)
{
	cout << "正方形析构函数" << endl;
}

float Square::area()
{
	return (width * width);
}

float Square::perimeter()
{
	return (4 * width);
}

void Square::setWidth(float b)
{
	width = b;
}

void Square::print()
{
	cout << "width:" << width << endl;
	cout << "area:" << area() << endl;
	cout << "perimeter:" << perimeter() << endl;
}

Rect::Rect()
{
	width = 0;
	height = 0;
}

Rect::Rect(float x, float y)
{
	width = x;
	height = y;
}

Rect::~Rect()
{
	cout << "矩形析构函数" << endl;
}

float Rect::area()
{
	return (width * height);
}

float Rect::perimeter()
{
	return (2 * (width + height));
}

void Rect::setWidth(float x, float y)
{
	width = x;
	height = y;
}

void Rect::print()
{
	cout << "width:" << width << endl;
	cout << "height:" << height << endl;
	cout << "area:" << area() << endl;
	cout << "perimeter:" << perimeter() << endl;
}



int main()
{
	float a = 0.0;
	float b = 0.0;
	cout << "请输入正方形的边长:";
	cin >> a;
	Square S(a);
	S.print();
	S.setWidth(5);
	S.print();
	cout << "请输入矩形的长:";
	cin >> a;
	cout << "请输入矩形的宽:";
	cin >> b;
	Rect R(a, b);
	R.print();
	R.setWidth(3, 4);
	R.print();
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值