为深拷贝散分!
#include<iostream>
using namespace std;
class point
{
public:
point()
{
x=y=0;
cout<<"default constructor called."<<endl;
}
point(int xx,int yy)
{
x=xx;
y=yy;
cout<<"constructor called."<<endl;
}
~point()
{
cout<<"destructor called."<<endl;
}
int getx()
{
return x;
}
int gety()
{
return y;
}
void move(int j,int k)
{
x=j;
y=k;
}
private:
int x,y;
};
class arrayofpoints
{
public:
arrayofpoints(int n)
{
numberofpoints=n;points=new point[n];
}
arrayofpoints(arrayofpoints&pointsarray);
~arrayofpoints()
{
cout<<"deleting..."<<endl;
numberofpoints=0;
delete[] points;
}
point&element(int n)
{
return points[n];
}
private:
point *points;
int numberofpoints;
};
arrayofpoints:: arrayofpoints(arrayofpoints&pointsarray)
{
numberofpoints=pointsarray.numberofpoints;
points=new point[numberofpoints];
for(int i=0;i<numberofpoints;i++)
points[i].move(pointsarray.element(i).getx(),pointsarray.element(i).gety());
}
int main()
{
int number;
cout<<"please enter the number of points:";
cin>>number;
arrayofpoints pointsarray1(number);
pointsarray1.element(0).move(5,10);
pointsarray1.element(1).move(15,20);
arrayofpoints pointsarray2(pointsarray1);
cout<<"copy of pointsarray1:"<<endl;
cout<<"point_0 of array2:"
<<pointsarray2.element(0).getx()
<<","<<pointsarray2.element(0).gety()<<endl;
cout<<"point_1 of array2:"
<<pointsarray2.element(1).getx()
<<","<<pointsarray2.element(1).gety()<<endl;
pointsarray1.element(0).move(25,30);
pointsarray1.element(1).move(35,40);
cout<<"after the moving of pointsarray1:"<<endl;
cout<<"point_0 of array2"
<<pointsarray2.element(0).getx()
<<","<<pointsarray2.element(0).gety()<<endl;
cout<<"point_1 of array2:"
<<pointsarray2.element(1).getx()
<<","<<pointsarray2.element(1).gety()<<endl;
}
其中实现深拷贝那段有些看不懂,也就是
arrayofpoints:: arrayofpoints(arrayofpoints&pointsarray)
{
numberofpoints=pointsarray.numberofpoints;
points=new point[numberofpoints];
for(int i=0;i<numberofpoints;i++)
points[i].move(pointsarray.element(i).getx(),pointsarray.element
辛苦各位高手了!不要吝啬你们的文字!讲细点!