我有一个带有私有内部类 CBar 的 CFoo 类。我想为 CFoo 实现一个流输出运算符,它又在其实现中使用 CBar 的流输出。当 CFoo 在公共命名空间中时,我可以让它工作,但是当我将它放在新的命名空间(命名空间 foobar)中时,操作员不能再访问私有内部类。我怀疑这与运算符的完整签名有关,但我无法找出指定朋友声明和实际运算符声明的正确方法,以便编译实现。谁能建议我可能会错过什么?请注意,如果流实现在标头中内联完成,它将编译,但我讨厌不必要地公开这样的实现!
在 foobar.h 中(只需注释掉 usefoobarnamespace 以测试非命名空间版本):
#define usefoobarnamespace
#ifdef usefoobarnamespace
namespace foobar
{
#endif // usefoobarnamespace
class CFoo
{
public:
CFoo() {}
~CFoo();
void AddBar();
private:
class CBar
{
public:
CBar() {m_iVal = ++s_iVal;}
int m_iVal;
static int s_iVal;
};
std::vector<CBar*> m_aBars;
friend std::ostream& operator<<(std::ostream& rcStream, CFoo& rcFoo);
friend std::ostream& operator<<(std::ostream& rcStream, CFoo::CBar& rcBar);
};
std::ostream& operator<<(std::ostream& rcStream, CFoo& rcFoo);
std::ostream& operator<<(std::ostream& rcStream, CFoo::CBar& rcBar);
#ifdef usefoobarnamespace
}
#endif // usefoobarnamespace
在 foobar.cpp 中:
#ifdef usefoobarnamespace
using namespace foobar;
#endif // usefoobarnamespace
int CFoo::CBar::s_iVal = 0;
CFoo::~CFoo()
{
std::vector<CBar*>::iterator barIter;
for (barIter = m_aBars.begin(); barIter != m_aBars.end(); ++barIter)
{
delete (*barIter);
}
}
void CFoo::AddBar()
{
m_aBars.push_back(new CBar());
}
std::ostream& operator<<( std::ostream& rcStream, CFoo& rcFoo )
{
rcStream<<"CFoo(";
std::vector<CFoo::CBar*>::iterator barIter;
for (barIter = rcFoo.m_aBars.begin(); barIter != rcFoo.m_aBars.end(); ++barIter)
{
rcStream<<(*barIter);
}
return rcStream<<")";
}
std::ostream& operator<<( std::ostream& rcStream, CFoo::CBar& rcBar )
{
return rcStream<<"CBar("<<rcBar.m_iVal<<")";
}