在 C++ 中,给定 A 类中的成员函数,我们是否可以将其访问限制为仅 B 类,而不给予 B 对 A 的完整友元访问权限?

发布于 2024-09-10 15:33:14 字数 465 浏览 4 评论 0原文

可能的重复:
干净的 C++ 粒度友元等效项? (答案:律师-委托人惯用语)

我已经想要这个好几次了,但一直没能想出一个像样的方法来做到这一点。

假设我在 A 类中有一个成员函数。我希望能够从不相关的 B 类调用该函数,但通常不能调用。您可能会说:“当然,将函数设为私有并声明 B 为 A 的友元。”这就是我一直在做的事情,但似乎有点过分了。我真的不想让 B 访问 A 中的所有内容,而只是访问一个函数。

简而言之:A::func() 只能由类 B 调用,但 B 未声明 A 的友元。可能吗?

Possible Duplicate:
clean C++ granular friend equivalent? (Answer: Attorney-Client Idiom)

I've wanted this a couple times and haven't been able to come up with a decent way to do it.

Say I've got a member function in class A. I want to be able to call that function from an unrelated class B, but not be generally callable. You might say, "Sure, make the function private and declare B to be a friend of A." That's what I've been doing, but it seems a bit overkill. I don't really want to give B access to everything in A, just the one function.

In short: A::func() callable only by class B, but B not declared a friend of A. Possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吃不饱 2024-09-17 15:33:14

您可以将A 的接口拆分为几个纯抽象基类,然后为B 提供对具有适当方法的接口的引用。其他类只会获取不包含此方法的接口。请记住,这不太可扩展,因为接口的数量很快就会变得非常大。

You could split the interface of A into several pure abstract base classes and then give B a reference to the interface that has the appropriate method. Other classes would only get interfaces that do not contain this method. Keep in mind that this is not very scalable, as the number of interfaces can quickly become very large.

千笙结 2024-09-17 15:33:14

一种可能的方法是创建一个包装 A::func 的受信任类,并将包装器对象传递给 B。这再次要求包装器是 A 的友元,但您只需要管理一个这样的类,而所有外部类都可以使用包装器。

例子:

class Wrapper;

class A {
  private:
    void func();
    /* other methods */

  public:
    Wrapper getWrapper();

    friend class Wrapper;
};

class Wrapper {
  private:
    A &ref;

  private:
    Wrapper(A &obj) : ref(obj) { }

  public:
    void func() {
      ref.func();
    }

  friend class A;
};

Wrapper A::getWrapper() {
  return Wrapper(*this);
}

One possible way might be to create a trusted class that wraps A::func and pass a wrapper object to B. This again requires the wrapper to be a friend of A, but you only need to manage one such class, while all external classes can make use of the wrapper.

Example:

class Wrapper;

class A {
  private:
    void func();
    /* other methods */

  public:
    Wrapper getWrapper();

    friend class Wrapper;
};

class Wrapper {
  private:
    A &ref;

  private:
    Wrapper(A &obj) : ref(obj) { }

  public:
    void func() {
      ref.func();
    }

  friend class A;
};

Wrapper A::getWrapper() {
  return Wrapper(*this);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文