c++ 友元

利用工作之余, 看了一天的友元居然都不理解, 第二天中午睡觉醒来后, 奇迹般的懂了, 把代码记录下来以防以后不懂

 

 作用及特点

作用及特点
 
友元提供了不同类的成员函数之间、类的成员函数与一般函数之间进行数据共享的机制。通过友元,一个不同函数或另一个类中的成员函数可以访问类中的私有成员和保护成员。c++中的友元为封装隐藏这堵不透明的墙开了一个小孔,外界可以通过这个小孔窥视内部的秘密。
 
友元的正确使用能提高程序的运行效率,但同时也破坏了类的封装性和数据的隐藏性,导致程序可维护性变差。

 代码

这个代码是报错的, 因为对象是无法访问私有成员的;
#include <iostream>
#include "test.h"
using namespace std;

class Tdata
{
public:
    Tdata(int x, int y){
        xx = x;
        yy = y;
    }

    void print();

private:
  int xx;
  int yy;

};

void Tdata::print(){
    printf("%d, %d\n", xx, yy);
}

int main(int argc, char const *argv[]){
    Tdata mydata(12, 3);
    mydata.print();
    printf("%d\n", mydata.xx); // it's error;, object is don't accessing private;

    return 0;
}

 

 

那到底该如何使用呢, 看代码

#include<iostream>
#include<cmath>
using namespace std;
class Point
{
public:
    Point(double xx, double yy)
    {
        x = xx;
        y = yy;
    };
    void Getxy();
    friend double Distance(Point &a, Point &b); // 右元函数
private:
    double x, y;
};
void Point::Getxy()
{
    cout << "(" << x << "," << y << ")" << endl;
}

double Distance(Point &a, Point &b) // 在右元函数中可以访问私有
{
    double dx = a.x - b.x;
    double dy = a.y - b.y;
    return sqrt(dx*dx + dy*dy);
}
int main(void)
{
    Point p1(3.0, 4.0), p2(6.0, 8.0);
    p1.Getxy();
    p2.Getxy();
    double d = Distance(p1, p2);
    cout << "Distance is" << d << endl;
    return 0;
}

 

 注意事项

(1) 友元关系不能被继承。
(2) 友元关系是单向的,不具有交换性。若类B是类A的友元,类A不一定是类B的友元,要看在类中是否有相应的声明。
(3) 友元关系不具有传递性。若类B是类A的友元,类C是B的友元,类C不一定是类A的友元,同样要看类中是否有相应的申明。

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值