深浅拷贝问题

inspire2010 2010-12-21 05:02:21
下面的程序有点问题,关于深浅拷贝的,执行过程有点问题,大家看看:
#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 x,int y)
{ X=x; Y=y; }
private:
int X,Y;
};

class ArrayOfPoints
{
public:
ArrayOfPoints(int n)
{
numberOfPoints=n;
points=new Point[n];
}

~ArrayOfPoints()
{ cout<<"Deleting..."<<endl;
numberOfPoints=0;
delete[] points;
}

Point& Element(int n)
{
return points[n];
}
private:
Point *points;
int numberOfPoints;
};

void 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;
}
...全文
172 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
就想叫yoko 2010-12-21
  • 打赏
  • 举报
回复
如果你自己不写拷贝构造函数, 那么当用到拷贝构造函数时, 将默认生成一个并按浅拷贝复制, 什么叫浅拷贝呢? 比如你的对象有个数据成员是指针, 那么用拷贝构造函数生成的新对象的那个指针数据成员也将指向老对象的指针所指向的地址.
例如
class A
{
public:
int *p;
}
A a;
a.p = new int;
A b(a);
这时a对象和b对象的p指针将指向同一个地址, 这样问题就出来了, 当修改a对象*p的值, b对象*p的值也会修改, 更恐怖的是, 当a对象的p指针delete后, b对象的p指针也相当于delete过了
cj04124195 2010-12-21
  • 打赏
  • 举报
回复
c++的内容
貌似还好理解
luciferisnotsatan 2010-12-21
  • 打赏
  • 举报
回复
lz的代码里没见有拷贝构造函数...

class A
{
A(A &obj){...} //这个是拷贝构造函数

}
pur_e 2010-12-21
  • 打赏
  • 举报
回复
楼上+1

ArrayOfPoints类需要实现拷贝构造函数


ArrayOfPoints(const ArrayOfPoints& oth)
{
numberOfPoints=oth.numberOfPoints;
points=new Point[numberOfPoints];
for(int i=0;i<numberOfPoints;i++)
points[i]=oth.points[i];
}
jackyjkchen 2010-12-21
  • 打赏
  • 举报
回复
楼主只要记着,浅拷贝是传地址,深拷贝传内存内容就行了
luciferisnotsatan 2010-12-21
  • 打赏
  • 举报
回复
浅拷贝,就是把对象的内存块赋值一份,类似memcpy。成员变量有指针,就是仅复制了指针,两个指针指向相同的空间。
深拷贝是指把指针指向的内容也复制一份。

深拷贝需要自己写拷贝构造函数,没写的话,默认生成的是浅拷贝。
另外,通常重载了拷贝构造函数,同时也要把operate=也重载了。

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧