简体   繁体   English

如何使在某个命名空间中声明的类成为在全局范围内定义的其他类的朋友

[英]How to make a class declared inside some namespace to be friend of other class defined in global scope

I want class A::B to be the friend of C. There is another class with same name in namespace D. How can I do this.我希望类 A::B 成为 C 的朋友。在命名空间 D 中有另一个同名的类。我该怎么做。 In actual hierarchy, different classes may be in different headers.在实际的层次结构中,不同的类可能在不同的头中。

#include <iostream>
#include <cstdlib>
using namespace std;


class C
{
    friend class A::B;
};

namespace A
{
    class B
    {
    };
}

namespace D
{
    class B
    {
    };
}

int main()
{    
    cout << "Hello, friend!" << endl;
}

You need to forward declare class B (in the correct namespace) before class C :您需要在class C之前转发声明类B (在正确的命名空间中):

namespace A {
    class B;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM