有点疑问~~~

zhangzhongke007 2009-05-29 10:06:37

#include<iostream>
using namespace std;

class point
{
public:
point()
{
x=y=0;
cout<<"Default constructor called!"<<endl;
}
point(int a,int b)
{
x=a;
y=b;
cout<<"constructor called!"<<endl;
}
~point()
{
cout<<"Deconstructor called!"<<endl;
}
int get_x()
{
return x;
}
int get_y()
{
return y;
}
void move(int m,int n)
{
x=m;
y=n;
}
private:
int x;
int y;
};

class arrayofpoints
{
public:
arrayofpoints(int n)
{
numofpoints=n;
points=new point[n];
}

arrayofpoints(arrayofpoints&p)
{
numofpoints=p.numofpoints;
points=new point[numofpoints];
for(int i=0;i<numofpoints;i++)
{
points[i].move(p.element(i).get_x(),p.element(i).get_y());
}
}

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

point& element(int a)//这个形式……
{
return *(points+a);
}
private:
int numofpoints;
point *points;
};

void main()
{
arrayofpoints a1(2);
a1.element(0).move(1,5);
a1.element(1).move(6,7);

arrayofpoints a2(a1);
cout<<"copy of a1:"<<endl;
cout<<"point_0 of a2:"<<a2.element(0).get_x()<<' '<<a2.element(0).get_y()<<endl;
cout<<"point_1 of a2:"<<a2.element(1).get_x()<<' '<<a2.element(1).get_y()<<endl;

cout<<"After the moving of a1:"<<endl;
a1.element(0).move(7,8);
a1.element(1).move(35,78);
cout<<"point_0 of a2:"<<a2.element(0).get_x()<<' '<<a2.element(0).get_y()<<endl;
cout<<"point_1 of a2:"<<a2.element(1).get_x()<<' '<<a2.element(1).get_y()<<endl;
}

问题:其中

point& element(int a)
{
return *(points+a);
}

该这个形式如何解释啊?加&于不加&有何区别?
...全文
87 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
woods2001 2009-05-29
  • 打赏
  • 举报
回复
返回引用,开销小,不容易出现零食变量析构等问题
zgjxwl 2009-05-29
  • 打赏
  • 举报
回复
不加&会调用拷贝构造函数,会生成一个临时对象。。加&就返回它本身了。不生成临时对象。
liao05050075 2009-05-29
  • 打赏
  • 举报
回复
不加&将返回一个对象的拷贝,这样会有拷贝的开销
返回一个引用则没有
lpms26086 2009-05-29
  • 打赏
  • 举报
回复
楼上正解
surlover 2009-05-29
  • 打赏
  • 举报
回复
&返回的是一个引用
aaaa3105563 2009-05-29
  • 打赏
  • 举报
回复
帮顶·

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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