zoukankan      html  css  js  c++  java
  • 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
    ", xx, yy);
    }
    
    int main(int argc, char const *argv[]){
        Tdata mydata(12, 3);
        mydata.print();
        printf("%d
    ", 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的友元,同样要看类中是否有相应的申明。
  • 相关阅读:
    http 请求头设置缓存
    手把手教你开发chrome扩展一:开发Chrome Extenstion其实很简单
    django如何用邮箱代替用户名登录
    python函数式编程学习之map,reduce,filter,sorted
    python traceback学习(转)
    python logging模块学习(转)
    python pip安装lxml失败(转)
    python下性能提示
    python移植性提示
    python测试与调试提示
  • 原文地址:https://www.cnblogs.com/renfanzi/p/9243400.html
Copyright © 2011-2022 走看看