• 类中友元函数的应用


    类中友元函数则是为了访问私有变量,如类B需要访问类A中的私有变量,则代码如下:
     
    example  one:
     
    #include "stdafx.h"
    #include
    using namespace std;
    class B;                               //提前申明类B
    class A{
    public:
     A(){
     English=19;  
     };
     void between(B &b);        //类B为类A的成员函数
    private: 
     double English;
    };
    class B {
    public:
     B(){Eng_score=0;};
     friend void A::between(B &p);       //类A为类B的友元函数,此函数可以访问类A中的私有变量,如English
     private:
     double Eng_score;
    };
    void A::between(B &p){  
     p.Eng_score=English;    //直接访问English
      cout<<"Eng_score="<<p.Eng_score<<endl; 
     };
    int _tmain(int argc, _TCHAR* argv[])
    {
     A a;
     B b;
     a.between(b);         //引用类B的对象b
    while (1);
     return 0;
    }
     
     
     
     example  two:
     
     
     
    #include "stdafx.h"
    #include
    using namespace std;
    float RandomRge(float LB, float UB)
    {
    float x;       x = LB + (UB - LB) / (RAND_MAX)*(float)rand();  return (x);
    }
    class A{
    public:
    A(){
    English=100;
    };
    ~A(){};
    static double average(){
    count++;
    double ave;
    Math=RandomRge(60, 100);
    cout<<Math<<endl;
    Math+=Math;
    ave=Math/count;
    return ave;
    };
    public:
    double English;
    static double Math;
    static int count;
    };
    double A::Math=0;
    int A::count=0;
    class B {
    public:
    friend void friend_a(A &p){      //友元函数
    double ave;
    ave=p.average();
    cout<<"count="<<p.count<<" "<<"Math="<<p.Math<<" "<<"ave="<<ave<<endl;
    };
    };
    int _tmain(int argc, _TCHAR* argv[])
    {
    A a[6];
    for (int i=0;i<6;i++){
    friend_a(a[i]);
    }
    while (1);
    return 0;
    }
     
     
    example  three:
     
    #include "stdafx.h"
    #include
    using namespace std;
    class A;
    class B {
    private:
    int c = 100;
    public:
    friend void frifun(A &p, B &pp);
    };
    class A {
    public:
    A(double r1=0,double i1=0) {
    r = r1;
    i = i1;
    }
    friend void frifun(A &p, B &pp) {
    cout << p.r <<" "<< p.i <<" "<<pp.c<< endl;
    }
     
    public:
    double r;
    double i;
    };
    int main()
    {
    B pp;
    A a1(5, 6);
    frifun(a1,pp);
    while (1);
        return 0;
    }
     
     
     
     
     
  • 相关阅读:
    VisionPro CogDistanceSegmentSegmentTool工具的功能原理
    VisionPro CogDistanceSegmentLineTool工具
    VisionPro CogDistanceSegmentEllipseTool工具 几何测量工具
    VisionPro CogDistanceSegmentCircleTool工具 几何测量工具
    VisionPro CogDistancePointPointTool 几何测量工具
    VisionPro CogDistancePointSegmentTool工具 几何测量工具
    VisionPro CogDistancePointLineTool工具
    VisionPro CogDistancePointCircleTool工具
    VisionPro CogDistancePointEllipseTool工具
    VisionPro CogDistanceLineEllipseTool 几何测量工具
  • 原文地址:https://www.cnblogs.com/tangjunjun/p/11676683.html
Copyright © 2020-2023  润新知