相关疑难解决方法(0)

干净的C++粒度朋友相当于?(答案:律师 - 客户成语)

为什么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)

c++ design-patterns private friend

47
推荐指数
2
解决办法
7527
查看次数

这种面向密钥的访问保护模式是一种已知的习惯用法吗?

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一个friendBar,避免了更复杂的代理模式.

有谁知道这种方法是否已经有一个名称,即,是一个已知的模式?

c++ design-patterns access-control friend

47
推荐指数
2
解决办法
8985
查看次数

标签 统计

c++ ×2

design-patterns ×2

friend ×2

access-control ×1

private ×1