c++ - 访问命名空间中 operator<< 中的私有(private)类

标签 c++ namespaces operator-overloading inner-classes

我有一个带有私有(private)内部类 CBar 的类 CFoo。我想为 CFoo 实现一个流输出操作符,它在它的实现中使用 CBar 的流输出。当 CFoo 在公共(public)命名空间中时,我可以让它工作,但是当我将它放在新的命名空间(命名空间 foobar)中时,运算符(operator)不能再访问私有(private)内部类。我怀疑这与运算符的完整签名有关,但我无法找出指定友元声明和实际运算符声明的正确方法,因此实现可以编译。谁能建议我可能会遗漏什么? 请注意,如果流实现是在 header 中内联完成的,它编译,但我讨厌不必要地公开这样的实现!

在 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<<")";
}

最佳答案

只需将.cpp文件中的代码放入命名空间即可:

namespace foobar {

// your existing code

}

关于c++ - 访问命名空间中 operator<< 中的私有(private)类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1310922/

相关文章:

namespaces - “Lisp-1 vs Lisp-2”是否与具有静态类型的语言相关?

c++ - 包装指针如何与右值引用一起使用?

c++ - CMake 和 find_package 问题

动态的 php 命名空间

JavaScript 封装/JQuery

派生类上的 C++ 赋值运算符实现

c++ - 字符串类关系运算符重载

c++ - 返回结构指针

c++ - 在 C++ 中读取 PDB header

c++ - C++ 中的返回表达式检查条件