如何在另一个名称空间中从全局名称空间定义一个朋友类? [英] How do I define a friend class from the global namespace in another namespace?
问题描述
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.
我对类有相同的问题.
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); };
};
如果我将CBaseSD放在命名空间中,它将起作用.例如., 朋友类SD :: CBaseSD; 但我没有找到适用于全局名称空间的咒语.
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.
我正在使用g ++ 4.1.2进行编译.
I am compiling with g++ 4.1.2.
推荐答案
如问题下方的某些注释所述,问题中的代码似乎可以与我一起使用(Linux-Ubuntu-16.04,gcc版本5.4.0) ),前提是转发声明这样的朋友班.
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.
这篇关于如何在另一个名称空间中从全局名称空间定义一个朋友类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!