C++友元函數和友元類示例


#include "math.h"
#include<iostream> 
using namespace std; 

class Point 
{ 
public: 
    Point(double xx, double yy) 
    {
        x=xx; 
        y=yy; 
    }
    void Getxy(); 
    friend double Distance(Point &a, Point &b);        //類Point的友元函數
    friend class Yao;                //類Point的友元類
private: 
    double x, y; 
}; 


class Yao
{
public:
    double Multi(Point &a)
    {
        return a.x * a.y + 1;
    }
};



void Point::Getxy() 
{ 
    cout<<"("<<x<<","<<y<<")"<<endl; 
} 
double Distance(Point &a, Point &b)            //類Point的友元函數
{ 
    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);            //Distance是類Point的友元函數,不是成員函數
    cout<<"Distance is "<<d<<endl; 
    Yao yao;
    d = yao.Multi(p1);
    cout<<"Math.Multi is "<<d<<endl;
    return true;
}

友元的使用並不復雜,且缺了這玩意完全可以實現,但既然這么設計,就有它存在的合理性,在某些條件下使用它還是很方便的。另外需要注意的一點,編程時,濫用這個東西容易引起數據的安全問題,故需謹慎使用之。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM