baidu_32471379 2015-11-01 03:55 采纳率: 0%
浏览 1393

c++ 友元类的参数问题

#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="<<dist(mp1,mp2)<<endl;
return 0;
} 图片说明

#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="<<dist(mp1,mp2)<<endl;
return 0;
}
图片说明
为什么把dist的参数前面的地址符去掉结果变了
求大神指点

  • 写回答

2条回答 默认 最新

  • Flying_Home 2015-11-01 06:03
    关注

    double dist(Point &p1,Point &p2),该函数的形式参数,相当于是给实参取别名。
    double dist(Point p1,Point p2),该函数的形式参数,需要创建局部变量,并将实参的值复制到局部变量中。
    Point p1 = mp1,相当于是调用了函数Point (Point &p)。
    Point p2 = mp2,也相当于调用了函数Point (Point &p)。
    Point (Point &p)该函数叫做拷贝构造函数。

    具体可以查看一下C++拷贝构造函数相关知识。

    评论

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流