繁体   English   中英

两个班级与另一个 class 的成员 function 交朋友

[英]Two classes friending a member function from the other class

I've been trying to find a way to have two classes, where each class has a member function, and each member function is a friend of the other class.

为了显示:

#include <iostream>

class A;

class B
{
    friend void A::func_A(); // compiler error: invalid use of incomplete type 'class A'
public:
    void func_B() { std::cout << "Function B\n"; }
};

class A
{
    friend void B::func_B();
public:
    void func_A() { std::cout << "Function A\n"; }
};

int main()
{
    A a;
    B b;
    
    a.func_A();
    b.func_B();
}

我明白为什么会这样; A 仅被声明且未定义,因此 B 不能成为其成员 function func_A()的朋友,因为它不知道它是什么。 为了让 B 知道它的定义,class A 的定义必须高于 class B 的定义。 然后问题是相同的,除了它现在是 class A 无法访问 B 的成员 function。

我的问题是是否有办法解决这种循环依赖。 我知道 C++ 允许结交整个 class,这将解决此问题。 但是,据我所知,最好的做法是尽可能限制成员的可见性。

你可以做这样的事情,虽然它可能不值得麻烦。

class B {
  friend class AccessorForAFuncA;
};

class A {
  void func_A();
};

class AccessorForAFuncA {
private:
  static void DoThingsWithPrivatePartsOf(B*);
  friend void A::func_A();
};

AccessorForAFuncA是一个帮助器 class ,它代表A::funcA访问B的私有部分。 只有A::funcA被授予此间接访问权限。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM