在c++标准中,若友元函数的类在名字空间‘myNamespace’定义,那么友元函数和该类都是namespace ‘myNamespace’的成员
例如,在实现复数类Complex的运算符重载时,若有如下定义:
namespace myComplex
{
class CComplex
{
public:
friend CComplex operator +(const CComplex& refNewComp1, const CComplex& refNewComp2);
friend CComplex operator -(const CComplex& refNewComp1, const CComplex& refNewComp2);
friend CComplex operator *(const CComplex& refNewComp1, const CComplex& refNewComp2);
};
}
{
class CComplex
{
public:
friend CComplex operator +(const CComplex& refNewComp1, const CComplex& refNewComp2);
friend CComplex operator -(const CComplex& refNewComp1, const CComplex& refNewComp2);
friend CComplex operator *(const CComplex& refNewComp1, const CComplex& refNewComp2);
};
}
那么,这些友元函数要么在名字空间‘myComplex’作用域内实现,
要么加上作用域操作符 ‘::’,在其作用域外实现之。
CComplex myComplex::operator+(const CComplex& refNewComp1, const CComplex& refNewComp2)
试想,如果没有‘myComplex::’你可能说友元函数‘CComplex& operator+(const CComplex& refNewComp1, const CComplex& refNewComp2) ’是名字空间 ‘myComplex’的成员,但是编译器不那么认为,编译器认为该友元函数是全局命名空间的函数。