C++友元

C++友元认识

有时候需要定义一些函数,这些函数不是类的一部分,但又需要频繁的访问类的数据成员,这时可以将这些函数定义为该函数的友元函数。除了友元函数外,还有友元类,两者统称为友元。友元的作用是为了提高程序的运行效率,但是它破坏了类的封装性和隐藏性,使得非成员函数可以访问类的私有成员。

友元可以是一个函数,该函数被称为友元函数;友元也可以是一个类,该类被称为友元类。

1、同类对象间无私处

MyString::MyString(const MyString & other)
{
    int len = strlen(other._str);//这里直接访问了other对象的私有成员,所以同类之间无私处
    this -> _str = new char[len + 1];
    strcpy(this -> _str, other._str);
}
#include <iostream>

using namespace std;
class A
{
public:
    void dis(A &t)
    {
        cout<<t.x<<t.y<<t.z<<endl;
    }
private:
    int x;
    int y;
    int z;
};

int main()
{
    A a, b;
    a.dis(b);
    return 0;
}

2、异类对象间有友元

2.1、全局函数做友元函数

友元函数是可以之间访问类的私有成员的非成员函数。它是定义在类外的普通函数,它不属于任何类,但需要在类的定义中加以声明,声明时只需要在友元的名称前加上关键字friend。

2.2、类成员函数做友元函数

#include <iostream>
#include <math.h>

using namespace std;
class Point;

class PointManagement
{
public:
    double getDistance(Point &a, Point &b);
};

class Point
{
public:
    Point(double xx, double yy)
        :x(xx),y(yy)
    {

    }
    void Getxy();
    friend double PointManagement::getDistance(Point &a, Point &b);

private:
    double x, y;
};


double PointManagement::getDistance(Point &a, Point &b)
{
    double dx = a.x - b.x;
    double dy = a.y - b.y;
    return sqrt(dx * dx + dy * dy);
}

int main()
{
    Point a(1, 2);
    Point b(3, 4);
    PointManagement pm;
    double dis = pm.getDistance(a, b);
    cout<<dis<<endl;
    return 0;
}

2.3、友元类

#include <iostream>
#include <math.h>

using namespace std;

//声明为谁的友元,就可以通过谁的对象,访问其数据成员

class Point
{
public:
    Point(double xx, double yy)
        :x(xx),y(yy)
    {

    }
    friend class PointManagement;//友元类
private:
    double x, y;
};

class PointManagement
{
public:
    double getDistance(Point &a, Point &b);
};


double PointManagement::getDistance(Point &a, Point &b)
{
    double dx = a.x - b.x;
    double dy = a.y - b.y;
    return sqrt(dx * dx + dy * dy);
}

int main()
{
    Point a(1, 2);
    Point b(3, 4);
    PointManagement pm;
    double dis = pm.getDistance(a, b);
    cout<<dis<<endl;
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值