/*使用实验5-8的Rectangle类,创建一个指针数组,定义形式如下:
Rectangle *pRectangle[3];
然后在运行中输入三个矩形对象的宽度和高度,分别建立三个矩形对象,
把这些对象的地址分别存放到pRectangle数组中。
然后调用getArea和getPerimeter函数计算每个矩形的面积和周长,并显示出来。
(可在构造函数和析构函数中加入输出语句,检验程序执行的流程.)*/
#include <iostream>
#include<cstring>
using namespace std;
class rectangle
{
int length;
int width;
public:
rectangle(){};
void rec(int a,int b)
{
length=a;
width=b;
cout<<"create a rectangle."<<endl;
cout<<"length="<<length<<" ";
cout<<"width="<<width<<endl;
}
void area()
{
cout<<"area="<<2*(length+width)<<" ";
}
void perimeter()
{
cout<<"perimeter="<<length*width<<endl;
}
};
int main()
{
rectangle *r[2];
int a,b;
for(int i=0;i<=2;i++)
{
cin>>a>>b;
(*r+i)->rec(a,b);
(*r+i)->area();
(*r+i)->perimeter();
}
}
修改如下
/*使用实验5-8的Rectangle类,创建一个指针数组,定义形式如下:
Rectangle *pRectangle[3];
然后在运行中输入三个矩形对象的宽度和高度,分别建立三个矩形对象,
把这些对象的地址分别存放到pRectangle数组中。
然后调用getArea和getPerimeter函数计算每个矩形的面积和周长,并显示出来。
(可在构造函数和析构函数中加入输出语句,检验程序执行的流程.)*/
#include <iostream>
#include<cstring>
using namespace std;
class rectangle
{
int length;
int width;
public:
rectangle()
{
length = 0;
width = 0;
};
void rec(int a, int b)
{
length = a;
width = b;
cout << "create a rectangle." << endl;
cout << "length=" << length << " ";
cout << "width=" << width << endl;
}
void area()
{
cout << "area=" << length * width << " ";
}
void perimeter()
{
cout << "perimeter=" << 2 * (length + width) << endl;
}
};
int main()
{
rectangle r1;
rectangle r2;
rectangle* r[2] = { &r1,&r2 };
int a, b;
for (int i = 0; i <= 1; i++)
{
cin >> a >> b;
(*(r + i))->rec(a, b);
(*(r + i))->area();
(*(r + i))->perimeter();
}
return 0;
}
修改如下,供参考:
#include <iostream>
#include<cstring>
using namespace std;
class rectangle
{
int length;
int width;
public:
rectangle(int a,int b):length(a),width(b){cout<<"create a rectangle."<<endl;}
//void rec(int a,int b)
//{
// length=a;
// width=b;
// cout<<"create a rectangle."<<endl;
// cout<<"length="<<length<<" ";
// cout<<"width="<<width<<endl;
//}
void getPerimeter()
{
cout<<"perimeter="<<2*(length+width)<<endl;
}
void getArea()
{
cout<<"area="<<length*width<<" ";
}
~rectangle()
{
cout<<"rectangle has been destructor."<<endl;
}
};
int main()
{
rectangle *r[2];
int a,b;
for(int i=0;i<2;i++)//for(int i=0;i<=2;i++)
{
cin>>a>>b;
r[i] = new rectangle(a,b);//(*r+i)->rec(a,b);
r[i]->getArea(); //(*r+i)->area();
r[i]->getPerimeter();//(*r+i)->perimeter();
}
for(int i=0;i<2;i++)
delete r[i];
return 0;
}