在不同命名空间中具有相同名称的c++友类
C++ friend class with same name in different namespaces
我在不同的命名空间中有两个同名的类。我不能修改类的名称。我想给其中一个类添加一个方法,但不允许将其作为公共方法添加。另一个类是在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++/clinamespace 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"。
相关文章:
- 模板类无法识别友元运算符
- 我是否声明了部分专门化的友类?-非常困惑
- 如何使用友类对象访问私有成员函数
- 无法调用友类的构造函数
- 友类或友成员函数-前向声明和包含头
- c++如何正确声明友类的另一个类的方法
- 如何从抽象类的友类访问抽象类的私有成员
- 在不同命名空间中具有相同名称的c++友类
- 封装和友类
- 如何在使用装饰器和迭代器设计模式时声明友类
- c++友类无效使用不完整的OOP类型
- 声明工厂是基类的友类
- 具有更多模板参数的模板友类
- 两种声明模板友类的方法
- 创建并使用指向友类方法的函数指针
- 是否有一种方法可以将可变参数包中的所有类指定为模板的友类,以便使用operator=
- 成员函数Outer::f()不是类Outer::Inner的友类.为什么
- 在c++中,可以防止派生类被友类以外的类实例化吗?
- 用友类重载构造函数
- 声明C函数友类并返回C枚举数