c++ - 如何从另一个命名空间中的全局命名空间定义友元类?

标签 c++ namespaces global friend

在之前的问答 (How do I define friends in global namespace within another C++ namespace?) 中,给出了在引用全局命名空间中的函数的命名空间中创建友元 函数 定义的解决方案。

我对类(class)有同样的问题。

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 放入命名空间,它就可以工作;例如。, friend 类 SD::CBaseSD; 但我还没有找到适用于全局命名空间的咒语。

我正在使用 g++ 4.1.2 进行编译。

最佳答案

如问题下方的一些评论所述,问题中的代码似乎适用于我(Linux-Ubuntu-16.04,gcc 版本 5.4.0),前提是友元类是 forward-declared .

为了寻找答案,我遇到了this post这既解释了使友元类成为全局命名空间的正确技术,又回答了为什么需要以这种方式声明它。这是一个很好的线程,因为它引用了标准。

如前所述,全局命名空间的类必须先前向声明,然后才能用作命名空间内类的友元类。

关于c++ - 如何从另一个命名空间中的全局命名空间定义友元类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2236712/

相关文章:

c++ - 变量在 MFC 类中放置私有(private)关键字的差异

javascript - 在 JavaScript 中定义全局对象的实现独立版本

Python RegExp 全局标志

php - 如何检查一个类是否属于某个命名空间

swift - 命名空间 : How do you distinguish duplicate function names, 一个/各自的 .swift 文件?

c++ - 使用 C++11 选项编译 C++98 代码时,由于 Boost header 导致的不明确重载

gcc - ARM + gcc : global destructors not called after main() returns, 但构造函数是

c++ - 如何找到数组左侧和右侧的最大元素?

c++ - 在c中如何在没有 vector 和结构数组的情况下拥有可变数量的结构?

c++ - 没有为 opencv_contrib 创建 makefile