zoukankan      html  css  js  c++  java
  • C++中的友元函数

    以计算两点距离为例:

     1 class Point
     2 {
     3 public:
     4     Point()= default;
     5     Point(float x, float y) :_x(x), _y(y) {}
     6     float _x; float _y;
     7 };
     8 
     9 float cal(const Point& s1,const Point& s2)
    10 {
    11     float x = (s1._x - s2._x) * (s1._x-s2._x);
    12     float y = (s1._y - s2._y) * (s1._y-s2._y);
    13     return sqrt(x+y);
    14 
    15 }
    16 
    17 int main(int argc, char* argv[])
    18 {
    19     Point s1(1,2);
    20     Point s2(3,4);
    21     cout<<cal(s1,s2);
    22     return 0;
    23 }

    由于类Point中的函数全部是public的,所以这里并无明显错误,如果类Point的成员函数改为private则会出现问题,于是引入友元,解决方案:

     1 class Point
     2 {
     3 public:
     4     Point()= default;
     5     Point(float x, float y) :_x(x), _y(y) {}
     6 private:
     7     float _x; float _y;
     8     friend float cal(const Point& s1, const Point& s2);
     9 };
    10 
    11 float cal(const Point& s1,const Point& s2)
    12 {
    13     float x = (s1._x - s2._x) * (s1._x-s2._x);
    14     float y = (s1._y - s2._y) * (s1._y-s2._y);
    15     return sqrt(x+y);
    16 
    17 }
    18 
    19 int main(int argc, char* argv[])
    20 {
    21     Point s1(1,2);
    22     Point s2(3,4);
    23     cout<<cal(s1,s2);
    24     return 0;
    25 }

    由于外部函数不属于类,故要使得该函数与类产生关系,则需要使用friend。

    如果为这个计算函数引入一个管理类,然后使其成为该管理类的成员函数,又该如何,解决如下:

    class Point;
    class Manage
    {
    public:
        Manage() = default;
        float cal(const Point& s1, const Point& s2);
    
    };
    class Point
    {
    public:
        Point()= default;
        Point(float x, float y) :_x(x), _y(y) {}
    private:
        float _x; float _y;
        friend float Manage::cal(const Point& s1, const Point& s2);
    };
    float Manage::cal(const Point& s1, const Point& s2)
    {
        float x = (s1._x - s2._x) * (s1._x - s2._x);
        float y = (s1._y - s2._y) * (s1._y - s2._y);
        return sqrt(x + y);
    
    }
    
    int main(int argc, char* argv[])
    {
        Point s1(1,2);
        Point s2(3,4);
        Manage a;
        cout<<a.cal(s1,s2);
        return 0;
    }

    说明:

    类的前向声明只能说明这是一个类,但是它的大小以及其他属性一无所知,故只能用于函数的形参、引用及指针。

  • 相关阅读:
    HDFS原理分析之HA机制:avatarnode原理
    [转]Hessian——轻量级远程调用方案
    [转]成为Java顶尖程序员 ,看这11本书就够了
    [转]Java四种线程池的使用
    [转]Java多线程
    IntelliJ IDEA 快捷键
    [转]django 日志logging的配置以及处理
    [转]使用TortoiseGit处理代码冲突
    动软DbHelperSQL
    [转]Entity Framework 的实体关系
  • 原文地址:https://www.cnblogs.com/SunShine-gzw/p/15430207.html
Copyright © 2011-2022 走看看