c++-友元函数和友元类

2019-12-21 16:01:56来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

c++-友元函数和友元类

友元函数

  • 友元函数和友元类(破坏类的封装性)
  • 面向对象编程思想
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cmath>


using namespace std;

class Point;

class PointManager {
public:
    double PointDistance(Point &p1, Point &p2);
};

class Point
{

public:
    //声明全局函数 PointDistance 是我类Point类的一个友元函数。
    //friend double PointDistance(Point &p1, Point &p2);
    friend double PointManager::PointDistance(Point &p1, Point &p2);

    Point(int x, int y) {
        this->x = x;
        this->y = y;
    }


    int getX()
    {
        return this->x;
    }

    int getY()
    {
        return this->y;
    }
private:
    int x;
    int y;

};

double PointManager::PointDistance(Point &p1, Point &p2)
{
    double dis;
    int dd_x = p1.x - p2.x;
    int dd_y = p1.y - p2.y;

    dis = sqrt(dd_x*dd_x + dd_y *dd_y);

    return dis;
}

# if 0
double PointDistance(Point &p1, Point &p2)
{
    double dis;
    int dd_x = p1.x - p2.x;
    int dd_y = p1.y - p2.y;

    dis = sqrt(dd_x*dd_x + dd_y *dd_y);

    return dis;
}
#endif



int main(void)
{
    
    Point p1(1, 2);
    Point p2(2, 2);

    //cout << PointDistance(p1, p2) << endl;

    PointManager pm;
    cout << pm.PointDistance(p1, p2) << endl;

    return 0;
}

友元类

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>

using namespace std;

class A 
{
public:

    A(int a)
    {
        this->a = a;
    }

    void printA() {
        cout << "a = " << this->a << endl;
        // B objB(3000);
        // cout << objB.b << endl;
    }

    //声明一个友元类B
    friend class B;
private:
    int a;
};


class B
{
public:
    B(int b)
    {
        this->b = b;
    }
    void printB() {
        A objA(100);
        cout << objA.a << endl;
        cout << "b = " << this->b << endl;
    }
    friend class A;
private:
    int b;
};

int main(void)
{
    B bObj(200);

    bObj.printB();
    
    return 0;
}

原文链接:https://www.cnblogs.com/ygjzs/p/12076771.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:c++-变量,this指针,全局函数,成员函数,自定义数组类

下一篇:c++-重载运算符(+-,++,--,+=,-=,cin,cout)