将命名空间声明为类的朋友 [英] Declaring a namespace as a friend of a class
问题描述
我想知道是否有一种方法可以让我们在一个特定的命名空间 friend
中定义所有函数和一个类?
I was wondering if there is a way such that we make all functions defined within a specific namespace friend
with a class?
特别是我有一个类,例如:
In particular, I have a class, for example:
class C {
private:
// ...
public:
// ...
friend C* B::f1(C*);
friend C* B::f2(C*);
friend C* B::f3(C*);
friend C* B::f4(C*);
friend C* B::f5(C*);
};
和命名空间 B
为:
namespace B {
C* f1(C* x);
C* f2(C* x);
C* f3(C* x);
C* f4(C* x);
C* f5(C* x);
};
现在,我宁愿避免在类定义中写 5 行,以使名称空间 B
的所有五个函数与类 C
成为朋友,并告诉编译器在命名空间 B
中定义的所有函数都是类 C
的朋友(即可以访问其私有成员).
Now, I would prefer to avoid writing 5 lines in the class definition to make all five functions of the namespace B
friend with class C
and just tell the compiler that all of the functions defined within the namespace B
are friends with the class C
(i.e. can access its private members).
我猜的一个快速解决方法是将命名空间更改为类并将函数定义为其静态成员,然后将类 B
声明为类 C
的朋友.但是,出于好奇,我想知道命名空间是否也可以实现这样的事情?
A quick fix I guess is to change the namespace to a class and define the functions as its static members and then declare the class B
as a friend of class C
. However, out of curiosity I was wondering if such thing is possible with namespaces as well or not?
提前致谢.
推荐答案
不,不可能与命名空间成为朋友.如果不出意外,这将构成安全漏洞",因为命名空间可以扩展到任何地方.因此,任何人都可以向命名空间添加任意函数并访问该类的非公开数据.
No, it's not possible befriend a namespace. If nothing else, it would constitute a "security breach," as namespaces can be extended anywhere. So anyone could add an arbitrary function to the namespace and access the class's non-public data.
最接近的是您提出的解决方案,使这些函数成为类的静态成员并与类成为朋友.但话说回来,为什么不首先使它们成为原始类(代码中的C
)的静态成员?
The closest you can get is the solution you propose, making those functions static members of a class and befriending the class. But then again, why not make them static members of the original class (C
in your code) in the first place?
顺便说一句,如果我在我的代码中遇到了这么多友元函数的需求,那会让我重新考虑我的设计,很难;我会认为这是我做错了什么.
As an aside, if I ran into a need for so many friend functions in my code, it would make think again about my design, hard; I'd take it as a sign I'm doing something wrong.
这篇关于将命名空间声明为类的朋友的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!