为什么C++有public
成员,任何人都可以调用和friend
声明所有 private
成员公开给定的外部类或方法,但没有提供语法将特定成员暴露给给定的调用者?
我想表达一些例程的接口,这些例程只能由已知的调用者调用,而不必让那些调用者完全访问所有的私有,这感觉是一个合理的想法.我能想出的最好的(下面)和其他人的建议到目前为止围绕着成语/不同间接性的模式,我真的只想要一种方法来获得单一的,简单的类定义,明确指出哪些来电者(比我更细粒度),我的孩子,或绝对任何人)可以访问哪些成员.表达以下概念的最佳方式是什么?
// Can I grant Y::usesX(...) selective X::restricted(...) access more cleanly?
void Y::usesX(int n, X *x, int m) {
X::AttorneyY::restricted(*x, n);
}
struct X {
class AttorneyY; // Proxies restricted state to part or all of Y.
private:
void restricted(int); // Something preferably selectively available.
friend class AttorneyY; // Give trusted member class private access.
int personal_; // Truly private state ... …
Run Code Online (Sandbox Code Playgroud) Matthieu M.在我之前看过的这个答案中提出了一种访问保护模式,但从未有意识地考虑过一种模式:
class SomeKey {
friend class Foo;
SomeKey() {}
// possibly make it non-copyable too
};
class Bar {
public:
void protectedMethod(SomeKey);
};
Run Code Online (Sandbox Code Playgroud)
这里只有一个friend
关键类可以访问protectedMethod()
:
class Foo {
void do_stuff(Bar& b) {
b.protectedMethod(SomeKey()); // fine, Foo is friend of SomeKey
}
};
class Baz {
void do_stuff(Bar& b) {
b.protectedMethod(SomeKey()); // error, SomeKey::SomeKey() is private
}
};
Run Code Online (Sandbox Code Playgroud)
它允许更多的细粒度访问控制不是制造Foo
一个friend
的Bar
,避免了更复杂的代理模式.
有谁知道这种方法是否已经有一个名称,即,是一个已知的模式?