| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 518 人关注过本帖
标题:公有成员函数与友元函数的转换
只看楼主 加入收藏
魔鬼鱼
Rank: 1
等 级:新手上路
帖 子:6
专家分:0
注 册:2011-3-25
结帖率:100%
收藏
 问题点数:0 回复次数:3 
公有成员函数与友元函数的转换
#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),请修改主函数中的相应代码时程序功能不变。





搜索更多相关主题的帖子: return 
2011-05-09 20:26
monicamlg
Rank: 2
等 级:论坛游民
帖 子:7
专家分:13
注 册:2011-3-18
收藏
得分:0 
//#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 编辑 ]
2011-10-19 12:34
monicamlg
Rank: 2
等 级:论坛游民
帖 子:7
专家分:13
注 册:2011-3-18
收藏
得分:0 

#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;
}
不好意思 这样更简单
2011-10-28 13:41
快速回复:公有成员函数与友元函数的转换
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.011424 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved