C++类封装计算矩形的周长、面积,改变矩形大小方法

用C++的方法实现矩形的周长、面积的计算

首先要创建一个矩形类,包括其基本属性:长和宽

通过构造函数对所创建的对象进行初始化赋值

再次自定义成员函数,实现周长、面积的计算

通过public里面自定义的Change函数,实现对已有对象的访问,并对已有变量实现重新赋值

#include<iostream>

using namespace std;

class Rectangle
{
private:
	double length, width;//定义矩形的长和宽
public:
	Rectangle()
	{
		length = width = 0.0;
	}
	Rectangle(double x, double y)
	{//赋值构造函数,对矩形的长和宽进行赋值
		length = x;
		width = y;
	}
	~Rectangle()
	{
		cout << "析构函数调用" << endl;
	}
	void Print()
	{
		cout << "length = " << this->length << endl;
		cout << "width = " << this->width << endl;
	}
	double Zhouchang(Rectangle const& temp);
	double Area(Rectangle const& temp);
	void Change_length(double a);
	void Change_width(double a);
};

double Rectangle::Zhouchang(Rectangle const& temp)
{
	return (temp.length + temp.width) * 2;
}

double Rectangle::Area(Rectangle const& temp)
{
	return temp.length * temp.width;
}

void Rectangle::Change_length(double a)
{
	length = a;
}

void Rectangle::Change_width(double a)
{
	width = a;
}

int main()
{
	double x, y;
	cout << "输入矩形的长和宽:" << endl;
	cin >> x >> y;
	Rectangle a(x, y);
	cout << "矩形的周长为:" << endl;
	cout << a.Zhouchang(a) << endl;
	cout << "矩形的面积为:" << endl;
	cout << a.Area(a) << endl;
	double m, n;
	cout << "改变矩形的长为:" << endl;
	cin >> m;
	a.Change_length(m);
	cout << "矩形的长和宽为:" << endl;
	a.Print();//打印出矩形的长和宽
	cout << "改变矩形的宽为:" << endl;
	cin >> n;
	a.Change_width(n);
	cout << "矩形的长和宽为:" << endl;
	a.Print();//打印出矩形的长和宽
	return 0;
}

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值