在不同命名空间中具有相同名称的c++友类

C++ friend class with same name in different namespaces

本文关键字:c++ 友类 命名空间      更新时间:2023-10-16

我在不同的命名空间中有两个同名的类。我不能修改类的名称。我想给其中一个类添加一个方法,但不允许将其作为公共方法添加。另一个类是在c++/CLI中作为ref类编写的,需要访问这个方法。我试着使用friend类,但是我不知道如何使用它。

标准c++中的

dll:

namespace X
{
    class A
    {
        protected:
        __declspec(dllexport) void method();
    }
}

应用于c++/CLI

namespace Y
{
    ref class A
    {
        void someMethod()
        {
            X::A otherClass;
            otherClass.method();
        }
    }
}

我试过以下方法:朋友班Y::A;//编译错误C2653: Y不是类或命名空间名称

当我声明命名空间Y时,我得到错误C2039: 'A':不是'Y'的成员

我不能在命名空间Y中添加类a的前向声明,因为类a是用标准c++编译的,在前向声明中我必须将其声明为ref class。

编译器:Visual Studio 2008

有谁有主意吗?

谢谢

解决方案(由于Sorayuki):

#ifdef __cplusplus_cli
    #define CLI_REF_CLASS ref class
#else
    #define CLI_REF_CLASS class
#endif
namespace Y { CLI_REF_CLASS A; }
namespace X
{
    class A
    {
        protected:
        friend CLI_REF_CLASS Y::A;
        __declspec(dllexport) void method();
    }
}

我不确定这种把戏是否被允许。

但也许你想看看这种"黑客":

在c++/cli

namespace Y
{
    class HackA : public X::A {
        public:
        void CallMethod() { method(); }
    };
    ref class A
    {
        void someMethod()
        {
            X::A otherClass;
            assert(sizeof(HackA) == (X::A));
            HackA* p = (HackA*) &otherClass;
            p->CallMethod();
        }
    };
};
编辑:

我已经测试了它可以通过编译

namespace Y { ref class A; };
namespace X
{
    class A
    {
        friend ref class Y::A;
        protected:
        __declspec(dllexport) void method();
    };
};
namespace Y
{
    ref class A
    {
        void someMethod()
        {
            X::A otherClass;
            otherClass.method();
        }
    };
};

也许你只需要复制X::A的头文件,并通过在命名空间X之前添加声明(而不是定义)Y::A来编辑副本,并包含"copy"。