用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;
}
|