《C++ Primer》第五版,中文版。242 页。
能不能给个例子?看书上的描述看不明白。
252 好像讲的就是这个问题。
在类申明里加上friend申明函数,在类外面定义函数。
http://blog.chinaunix.net/uid-790245-id-2037327.html
大概有下面两种情况需要使用友元函数:(1)运算符重载的某些场合需要使用友元。(2)两个类要共享数据的时候。
优点:能够提高效率,表达简单、清晰。
缺点:友元函数破环了封装机制,尽量不使用成员函数,除非不得已的情况下才使用友元函数。
定义全局的独立函数:
const SpreadsheetCell operator+(const SpreadSheetCell& lhs,
const SpreadsheetCell& rhs)
{
SpreadsheetCell newCell;
newCell.set(lhs.mValue + rhs.mValue);
return (newCell);
}
然后需要使用的类中申明为友元:
class SpreadsheetCell
{
……
friend const SpreadsheetCell operator+(const SpreadSheetCell& lhs,
const SpreadsheetCell& rhs);
……
}
使用时记住参数给正确。
跟普通函数的声明一样一样的
class A
{
public:
friend class B;
A(xxx);
private:
。。。
};