本例對C++友元的使用從代碼上做了一個簡單的概括,但不只限於本問講到的用法,友元還能夠重載等。
**ios
/全局函數做爲友元/函數
**spa
using namespace std;code
class Point{
public:orm
Point(double x, double y){ _x = x; _y = y; } void getFormatxy(); friend double distance(Point &a, Point &b);
private:對象
double _x, _y;
};繼承
void Point::getFormatxy(){get
cout<<"("<<_x<<","<<_y<<")"<<endl;
}
double distance(Point &a, Point &b){io
double dx = a._x - b._x; double dy = a._y - b._y; return sqrt(dx*dx + dy*dy);
}class
int main()
{
Point p1(3.0, 4.0), p2(6.0, 8.0); p1.getFormatxy(); p2.getFormatxy(); double d = distance(p1, p2); cout<<"distance is "<<d<<endl; return 0;
}
**
/一個類的成員函數做友元/
**
using namespace std;
class Point; //前向聲明,用於聲明。
class ManagerPoint{
public:
double distance(Point &a, Point &b);
};
class Point{
public:
Point(double x, double y){ _x = x; _y = y; } void getFormatxy(); friend double ManagerPoint::distance(Point &a, Point &b);
private:
double _x, _y;
};
void Point::getFormatxy(){
cout<<"("<<_x<<","<<_y<<")"<<endl;
}
double ManagerPoint::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()
{
Point p1(3.0, 4.0), p2(6.0, 8.0); p1.getFormatxy(); p2.getFormatxy(); ManagerPoint mp; float d = mp.distance(p1, p2); cout<<"distance is"<<d<<endl; return 0;
}
**
/友元類/
**
using namespace std;
class Point{
public:
friend class ManagerPoint; Point(double x, double y){ _x = x; _y = y; } void getFormatxy();
private:
double _x, _y;
};
void Point::getFormatxy(){
cout<<"("<<_x<<","<<_y<<")"<<endl;
}
class ManagerPoint{
public:
double distance(Point &a, Point &b);
};
double ManagerPoint::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()
{
Point p1(3.0, 4.0), p2(6.0, 8.0); p1.getFormatxy(); p2.getFormatxy(); ManagerPoint mp; float d = mp.distance(p1, p2); cout<<"distance is"<< d<<endl; return 0;
}
**
/友元小結/
**
//友元聲明以關鍵字friend開始,它只能出如今類定義中
//由於友元不是類受權的成員,因此它不受其所在區域的public private 和protected 的影響
//一般,把全部友元聲明組織在一塊兒並放在類頭以後.
//友元利弊:
//友元不是類成員,可是它能夠經過對象訪問類中的私有成員,友元的做用在於提升程序的運行效率
//可是,它破壞了封裝性,使得非成員函數能夠訪問類的私有成員
//注意: 友元關係不能被繼承,友元關係不具備傳遞性
using namespace std;
class Time{
public:
friend class Watch; Time(int hour, int min, int sec){ m_iHour = hour; m_iMinute = min; m_iSecond = sec; }
private:
int m_iHour; int m_iMinute; int m_iSecond;
};
class Watch{
public:
Watch(Time t): m_tTime(t){} void display(){ cout<<m_tTime.m_iHour<<endl; cout<<m_tTime.m_iMinute<<endl; cout<<m_tTime.m_iSecond<<endl; }
public:
Time m_tTime;
};
int main()
{
Time t(6, 30, 20); Watch w(t); w.display(); return 0;
}