[英]Allowing access to protected member function for class outside of namespace
Consider the following code:考虑以下代码:
namespace A
{
class B
{
protected:
friend class C;
static void foo();
};
}
class C
{
public:
C() { A::B::foo(); }
};
int main()
{
C c;
return 0;
}
As currently constructed, this code will not compile - the friendship declared in class B
applies to a (currently non-existent) A::C
, and not the C
in the global namespace.按照当前的构造,此代码将无法编译 - 在
class B
中声明的友谊适用于(当前不存在的) A::C
,而不是全局命名空间中的C
。 How can I work around this effectively, assuming I cannot add C
to non-global namespace?假设我无法将
C
添加到非全局命名空间,我该如何有效地解决这个问题? I have tried using friend class::C;
我试过用
friend class::C;
, but the compiler does not like that. ,但编译器不喜欢这样。 I have also tried forward declaring
class C;
我也尝试过向前声明
class C;
before the namespace A
scope, but that does not appear to work either.在
namespace A
scope 之前,但这似乎也不起作用。
The class C firstly is declared in the class B within namespace A. That is within the namespace A there is introduced the class C due to the elaborated type specifier and there is no previous declaration of the class. The class C firstly is declared in the class B within namespace A. That is within the namespace A there is introduced the class C due to the elaborated type specifier and there is no previous declaration of the class.
The class C declared in the global namespace is a different class.在全局命名空间中声明的 class C 是不同的 class。
You need at first to declare the class C in the global namespace as您首先需要在全局命名空间中将 class C 声明为
class C;
namespace A
{
class B
{
protected:
friend class C;
static void foo() {
std::cout << "Hello World!\n";
}
};
}
class C
{
public:
C() { A::B::foo(); }
};
In this case there is no need to use the elaborated type specifier在这种情况下,不需要使用详细的类型说明符
friend class C;
You could just write你可以写
friend C;
Otherwise without the forward declaration of the class C in the global namespace you need to declare the class C in the namespace A like否则,如果在全局命名空间中没有 class C 的前向声明,您需要在命名空间中声明 class Z0D61F8370A411D412F870B
namespace A
{
class B
{
protected:
friend class C;
static void foo() {
std::cout << "Hello World!\n";
}
};
}
namespace A
{
class C
{
public:
C() { B::foo(); }
};
}
And in main you need to write主要是你需要写
A::C c;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.