构建一个球类Ball,其成员为球心坐标(x,y,z)和球半径r,并设计构造函数(可以赋初值也可以不赋初值),复制构造函数,析构函数(打印信息,表示其被调用),设置新值成员函数Set(), 取球心坐标成员函数GetX()、GetY()、GetZ(),取球半径成员函数GetR(),打印成员值成员函数Print(),计算球体积成员函数Volume()。并用此类分别定义长度为10的静态对象数组,长度为20的动态对象数组,每个对象的球心坐标(x,y,z)和球半径r由随机数rand()产生(球半径r的值应该为正数),打印每个球对象的(x,y,z)、r和体积;然后分别将对象数组按照其r值从小到大排序,并打印排序后每个对象的(x,y,z)、r和体积;并计算打印出所有对象的平均(x,y,z)、平均r和平均体积。(并释放动态对象数组,注意析构顺序与构造顺序的不同。)
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
class ball
{
public:
ball(int x=0,int y=0, int z=0,int r=0):x(x),y(y),z(z),r(r){}
ball(ball &b){x=b.x;y=b.y;z=b.z;r=b.r;}
~ball(){cout<<"destructor!"<<endl;}
void set(int x,int y,int z,int r){this->x=x;this->y=y;this->z=z;this->r=r;}
void print(){cout<<"球心坐标为("<<x<<","<<y<<","<<z<<") 半径为"<<r;}
int GetX(){return x;}
int GetY(){return y;}
int GetZ(){return z;}
int GetR(){return r;}
double volume(){return 4/3*3.14*r*r*r;}
private:
int x,y,z,r;
};
void bubsort(ball *d,int n)
{
int i,j;
ball temp;
bool change;
for(i=n,change=true;i>0&&change;--i)
{
change=false;
for(j=0;j<i;++j)
if(d[j+1].GetR()<d[j].GetR())
{
temp=d[j+1];
d[j+1]=d[j];
d[j]=temp;
change=true;
}
}
return;
}
void main()
{
int i,x=0,y=0,z=0,r=0;
double v=0;
ball b[10],*c,d[30];
c=new ball[20];
srand((unsigned int)time(NULL));
for(i=0;i<10;i++)
{
b[i].set(rand()%100,rand()%100,rand()%100,abs(rand()%100));
d[i]=b[i];
b[i].~ball();
}
for(i=0;i<20;i++)
{
c[i].set(rand()%100,rand()%100,rand()%100,abs(rand()%100));
d[i+10]=c[i];
c[i].~ball();
}
for(i=0;i<30;i++)
{
d[i].print();
cout<<" 该球体积为"<<d[i].volume()<<endl;
}
cout<<"*******************************************排序*****************************************"<<endl;
bubsort(d,30);
for(i=0;i<30;i++)
{
d[i].print();
cout<<" 该球体积为"<<d[i].volume()<<" ";
x+=d[i].GetX();y+=d[i].GetY();z+=d[i].GetZ();r+=d[i].GetR();v+=d[i].volume();
d[i].~ball();
}
cout<<"平均球心坐标为("<<double (x/30)<<","<<double (y/30)<<","<<double (z/30)<<") 平均半径为"<<double (r/30)<<" 平均体积为"<<v/30<<endl;
system("pause");
}
拍完序后总会有一个球的成员变量全部变成未初始化的数值 同时会提示堆被损坏 求高手帮助 这是为什么??