注册 登录
编程论坛 VC++/MFC

公有成员函数与友元函数的转换

魔鬼鱼 发布于 2011-05-09 20:26, 518 次点击
#include <stdafx.h>
#include <iostream.h>
#include <cmath>
class Point
{
       double x;
       double y;
public:
       Point(double a,double b)
       {
              x=a;
              y=b;
       }
       friend double dist(Point a,Point b);
};
double dist(Point a,Point b)
{
     return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
void main()
{
     Point p1(1,2);
     Point p2(5,2);
     cout<<dist(p1,p2)<<endl;
}

将友元函数dist(point a,point b)改为Point类的公有成员函数 Point ::dist(point &b),请修改主函数中的相应代码时程序功能不变。





3 回复
#2
monicamlg2011-10-19 12:34
//#include <stdafx.h>
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
       double x;
       double y;
public:
       Point(double a,double b)
       {
              x=a;
              y=b;
       }
     Point();
     double dist(Point & c);
     Point operator-(const Point & t)const;
 };
Point::Point()
{
    x=y=0;
}
Point Point::operator-(const Point & t)const
{
  Point s;
  s.x=x-t.x;  
  s.y=y-t.y;
  return s;
}
 double Point::dist(Point & c)
{
   return sqrt(c.x*c.x+c.y*c.y);
}

void main()
{
    Point p1(1,2);
    Point p2(5,2);
    Point p3;
    p3=p1-p2;
    cout<<p3.dist(p3)<<endl;
}
这个程序我已经调试了 是正确的,你试试看

     

[ 本帖最后由 monicamlg 于 2011-10-28 13:35 编辑 ]
#3
monicamlg2011-10-28 13:41

#include <iostream.h>
#include <cmath>
class Point
{
       double x;
       double y;
public:
       Point(double a,double b)
       {
              x=a;
              y=b;
       }
      double dist(Point &b );
};
double Point::dist(Point &b)
{
     return sqrt((x-b.x)*(x-b.x)+(y-b.y)*(y-b.y));
}
void main()
{
     Point p1(1,2);
     Point p2(5,2);
     cout<<p1.dist(p2)<<endl;
}
不好意思 这样更简单
1