开发者社区 问答 正文

c++友元函数形参的问题

友元类函数的定义是 friend double dist(Point &p1,Point &p2);
但是 把&去掉 friend double dist(Point p1,Point p2);
不会提示错误 反而调用了复制构造函数是为什么?
#include
#include
using namespace std;
class Point
{
public:
Point (int x=0,int y=0):x(x),y(y)
{
cout<<"构造函数被调用"<<endl;
}
Point (Point &p)
{
cout<<"复制构造函数被调用"<<endl;
x=p.x;
y=p.y;
}
friend double dist(Point &p1,Point &p2);
private:
int x,y;
};
double dist(Point &p1,Point &p2)
{
double x=p2.x-p1.x;
double y=p2.y-p1.y;
return sqrt(x*x+y*y);
}
int main()
{
Point mp1(1,1),mp2(4,5);
cout<<"len=";
cout<<dist(mp1,mp2)<<endl;
return 0;
}

展开
收起
a123456678 2016-03-06 17:48:47 2098 分享 版权
1 条回答
写回答
取消 提交回答
  • 把&去掉之后,在函数调用过程中,参数传递就是复制要传入的参数生成另外一个变量(要构造一个变量所以要调用构造函数)传入函数(此处为友元函数,其他函数也是这样子)。
    函数调用完成之后,复制生成的变量自动调用析构函数释放。如果不去掉&,则传入参数是一个引用,参数传递过程中就复制该引用
    (复制的引用是指向同一个变量的,在传递过程中并没有产生新的变量,所以不会调用构造函数)。你的疑问与友元函数没有多少关系,你可以了解一下函数调用过程。

    2019-07-17 18:54:58
    赞同 展开评论
问答分类:
C++
问答标签:
问答地址: