所以如果我不做自己的析构函数,我的代码运行正常。根据调试器和监视器(我可能不会正确使用它们),它会立即删除对象数组的成员。代码的目的是用矩形(宽度,高度,颜色)填充数组,然后在用户选择颜色后按降序(按表面积)打印出信息。此外,我的没有参数的构造函数与重载的运算符+(它应该通过添加它们的宽度和高度添加两个矩形)冲突。同样,代码编译并且在没有析构函数的情况下工作得很好,没有没有参数的构造函数("禁用"在下面的代码中)。
#include <iostream>
#include <string.h>
using namespace std;
class rectangle
{
private:
float width;
float height;
char *colour;
public:
// rectangle(){width=0;height=0;colour=0;}
rectangle(float, float, char *);
// ~rectangle();
float reWidth(){return width;}
float reHeight(){return height;}
char * reColour(){return colour;}
void changeWid(float a){width=a;}
void ChangeHei(float b){height=b;}
float area();
rectangle largerArea(rectangle);
void printInfo();
void showColour(rectangle *, int, char *);
friend rectangle operator+(rectangle,rectangle);
static float totalArea;
};
float rectangle::totalArea=0;
rectangle::rectangle(float a=0, float b=0, char *c=""):width(a),height(b)
{
colour=new char[strlen(c)];
strcpy(colour,c);
totalArea+=area();
}
/*rectangle::~rectangle()
{
delete colour;
colour=0;
}*/
float rectangle::area()
{
return width*height;
}
rectangle rectangle::largerArea(rectangle a)
{
if(a.area()>area())
return a;
else if(a.area()<area())
return *this;
else return a.width>=width?a:*this;
}
void rectangle::printInfo()
{
cout<<width<<" x "<<height<<" - "<<colour<<endl;
}
rectangle operator+(rectangle a, rectangle b)
{
rectangle temp;
if((a.width && b.width && a.height && b.height) !=0)
{
temp.width=a.width+b.width;
temp.height=a.height+b.height;
}
else if(b.height==0)
{
temp.width=a.width+b.width;
temp.height=a.height+b.width;
}
else if(a.height==0)
{
temp.width=a.width+b.width;
temp.height=a.width+b.height;
}
return temp;
}
void rectangle::showColour(rectangle* arrayr, int n, char* col)
{
int i,j;
rectangle temp;
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (arrayr[i].area() > arrayr[j].area())
{
temp = arrayr[i];
arrayr[i] = arrayr[j];
arrayr[j] = temp;
}
}
}
for(int i=0;i<n;i++)
if(strcmp(col,arrayr[i].colour)==0)
arrayr[i].printInfo();
}
int main()
{
float a,b;
char c[20];
cout<<"Insert info for rectangle A: ";
cin>>a>>b>>c;
rectangle A(a,b,c);
cout<<"A=";A.printInfo();
cout<<"Insert info for rectangle B: ";
cin>>a>>b>>c;
rectangle B(a,b,c);
cout<<"B=";B.printInfo();
cout<<"A+B=";(A+B).printInfo();
cout<<"A+3=";(A+3).printInfo();
cout<<"3+A=";(3+A).printInfo();
int n;
cout<<"Array length? : ";
cin>>n;
rectangle arrayr[n];
for(int i=0;i<n;i++)
{
cout<<"Insert info for "<<i+1<<"-th rectangle: ";
cin>>a>>b>>c;
arrayr[i]=rectangle(a,b,c);
}
char colour[20];
cout<<"Choose colour: ";
cin>>colour;
arrayr[1].showColour(arrayr,n,coulour);
cout<<"Total area of created rectangles is: "<<rectangle::totalArea;
}