How do I define a friend class from the global namespace in another namespace?

回眸只為那壹抹淺笑 提交于 2019-12-10 16:46:38

问题


In a previous Q&A (How do I define friends in global namespace within another C++ namespace?), the solution was given for making a friend function definition within a namespace that refers to a function in the global namespace.

I have the same question for classes.

class CBaseSD;

namespace cb {
class CBase
{
    friend class ::CBaseSD; // <-- this does not work!?
private:
    int m_type;
public:
    CBase(int t) : m_type(t) {};
};
}; // namespace cb

class CBaseSD
{
private:
    cb::CBase*  m_base;
public:
    CBaseSD(cb::CBase* base) : m_base(base) {};
    int* getTypePtr()
    { return &(m_base->m_type); };
};

If I put CBaseSD into a namespace, it works; e.g., friend class SD::CBaseSD; but I have not found an incantation that works for the global namespace.

I am compiling with g++ 4.1.2.


回答1:


As stated in some of the comments below the question, the code in the question appears to work with me (Linux-Ubuntu-16.04, gcc version 5.4.0), provided that the friend class was forward-declared.

In pursuit of an answer, I came across this post that both explains proper technique for making friend class of a global namespace and answers why it needs to be declared the way it does. It is a nice thread because it references the standard.

As stated earlier, the class of a global namespace must be forward declared before it can be used as a friend class to a class within a namespace.




回答2:


add the forward declaration like below

namespace {  
  // anonymous namespace declaration
  class CBaseSD;
}

then your normal

friend class CBaseSD;// no need of ::

works in CBase



来源:https://stackoverflow.com/questions/2236712/how-do-i-define-a-friend-class-from-the-global-namespace-in-another-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!