class 和 class 成员将使用的公共函数放在哪里?

Where to place common function which will be used by class and class member?

例如,

class B {
  int* b1;
  int* b2;
  B(int* x, int* y) {
     b1 = x;
     b2 = y;
  }

};

class A {
  int* a1;
  int* a2;
  B* b1;
  public:
  A() {
    a1 = new int;
    a2 = new int;
    b1 = new B1(a1, b1);
  }
};

我想从 class A 和 B 的对象访问 a1 和 a2 指向的值。我应该在哪里编写相同的函数,以便 A 的对象和对象可以调用该函数B.?

您可以与 类 成为好友,反之亦然。 look here.

这允许 "cross usage" 个成员和方法

如果您只想让一个函数同时访问 A 和 B 的私有成员和方法,您可以将此特定函数设为好友。

在这个特殊的上下文中,您只是传递指针,所以 a1a2 指向的对象 是 [=14= 指向的对象] 和 b2。另一方面,A 对象知道它包含什么 B,但是 B 的实例不知道 A.

中包含什么

因此,我认为操作指向对象的函数应该在B class 中声明。那么如果 B 的存在是 A 的 public API 的成员(例如 getter)就足够了:

class B {
    ...
    void do_something(...) {
        // do something with objects pointed by b1 and b2
    }
};
...
A a;
a.getB()->do_something();
...

如果 AB 成员是一个 实现细节 ,你应该在 A:

中声明一个中继方法
class A {
    ...
    void do_something(...) {     // delegate to the `B` member
        b1->do_something(...);
    }
};
...
A a;
a.do_something(...);
...