第六周 【项目4-成员函数、友元函数和一般函数有区别】

(1)阅读下面的程序,体会注释中的说明。

[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片

//例:使用成员函数、友元函数和一般函数的区别 

#include <iostream> 

using namespace std; 

class Time 

public: 

   Time(int h,int m,int s):hour(h),minute(m),sec(s) {} 

   void display1();    //display1是成员函数 

   friend void display2(Time &); //display2是友元函数 

   int getHour(){return hour;} 

   int getMinute(){return minute;} 

   int getSec(){return sec;} 

private: 

   int hour; 

   int minute; 

   int sec; 

}; 

void Time::display1()  //成员函数display1的实现,dispaly1前加Time:: 

   //以hour形式直接访问私有数据成员,实质是this->hour形式 

   cout<<hour<<":"<<minute<<":"<<sec<<endl; 

void display2(Time &t)  //友元函数dispaly2的实现,不加Time::,友元并不是类的成员 

   //虽然不是类的成员函数,却可以用t.hour的形式直接访问私有数据成员——这就是友元 

   cout<<t.hour<<":"<<t.minute<<":"<<t.sec<<endl; 

void display3(Time &t)  //display3是一般函数,dispaly3前不加Time:: 

   //不能直接访问,只能用公共接口t.getHour()形式访问私有数据成员 

   cout<<t.getHour()<<":"<<t.getMinute()<<":"<<t.getSec()<<endl; 

int main() 

   Time t1(10,13,56); 

   t1.display1();  //成员函数这样调用:对象名.函数名() 

   display2(t1);   //友员函数的调用和一般函数无异(但实现中可以不同) 

   display3(t1);   //一般函数的调用 

   return 0; 

(2)模仿上面的示例,完成求点类中距离的任务。你需要实现求距离函数的三种版本:分别利用成员函数、友元函数和一般函数求两点间距离的函数,并设计main()函数完成测试。

提示:此项目和例子的区别在于“距离是一个点和另外一个点的距离”,不同版本在参数上有体现。三个版本建议分开测试,也可以如示例,放在一个程序中完成。

下面是点类的部分代码。

[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片

class CPoint   

private:   

   double x;  // 横坐标   

   double y;  // 纵坐标   

 public:  

   CPoint(double xx=0,double yy=0):x(xx),y(yy){}   

    ……//请继续写需要的代码 

}; 

[参考解答]

/*
*copyright (c) 2015,
*All rights reserved
*The Author:王争取
*Finished Time:2015.4.14
*/
#include <iostream>
#include <cmath>
using namespace std;
class CPoint
{
private:
    double x;  // 横坐标
    double y;  // 纵坐标
public:
    CPoint(double xx=0,double yy=0):x(xx),y(yy) {};
    void get_L1(CPoint &C);
    friend void get_L2(CPoint &C1,CPoint &C2);
    double get_x();
    double get_y();
};
void  get_L(CPoint &C1,CPoint &C2)
{
    double x1,y1;
    x1=C1.get_x()-C2.get_x();
    y1=C1.get_y()-C2.get_y();
    cout<<"一般函数求得:"<<(sqrt(x1*x1+y1*y1))<<endl;
}
double CPoint::get_y()
{
    return y;
}
double CPoint::get_x()
{
    return x;
}
void get_L2(CPoint &C1,CPoint &C2)
{
    double  x1,y1;
    x1=C1.x-C2.x;
    y1=C1.y-C2.y;
    cout<<"友函数求得:"<<(sqrt(x1*x1+y1*y1))<<endl;
}
void CPoint::get_L1(CPoint &C)
{
    double  x1,y1;
    x1=x-C.x;
    y1=y-C.y;
    cout<<"成员函数求得:"<<(sqrt(x1*x1+y1*y1))<<endl;
}
int main()
{
    CPoint c1(2,3),c2(6,6);//定义对象c1,c2
    c1.get_L1(c2);//调用成员函数
    get_L2(c1,c2);//调用友函数
    get_L(c1,c2);//调用一般函数
    return 0;
}



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值