c++ - 前向声明的替代方案 : two classes using each other

标签 c++ inheritance abstract-class forward-declaration

我有 A 类,它必须实现一些功能。由于实现其中一个需要它自己的数据结构,我假设 A 包含另一个类 B,它具有所有需要的数据结构和函数。但是,B 也需要使用 A 的数据结构和功能。我使用了两个使用前向声明相互调用的类。但仍然存在问题。例如,我需要公开 A 中的所有数据结构,以便 B 可以访问它。我尝试使用友元类,但是当我将 B 声明为具有实现 B 功能的子类的抽象类时,我需要将 A 的所有数据结构公开。因为 friend 类不适用于继承的子类,所以 A 的所有数据结构都需要公开。这使我的设计非常困惑。

class B; 
class A{
protected: 
    int ds[100];
    B * b; 
public:
    a_func(){ 
        b->b_func(); 
    }
};


class A; 
class B{
    A * a; 
public: 
    b_func(){
        a->a_func(); 
    }
};

class sub_B:public B{
public: 
    b_func(){
        a->a_func(); 
        a->ds ...; 
    }
}

我的问题是:有没有其他设计?

最佳答案

您不必在类定义中提供成员函数定义:

class A;
class B;
class A {
  // no need for public
  B * b;
  void a_funct(void);
};
class B {
  // no need for public here, too
  A * a;
  void b_funct(void);
};
// the following goes in a source file,
// otherwise you should mark it as inline
void A::a_funct() {
  b->b_funct();
}
void B::b_funct() {
  a->a_funct();
}

请注意,上面的代码仅作为示例,在其当前形式下,它只不过是一个花哨的无限(递归)循环。

关于c++ - 前向声明的替代方案 : two classes using each other,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31223410/

相关文章:

java - 为什么我们不能将 Cloneable 作为抽象类而不是将其作为接口(interface)?

c++ - boost::可选抽象类类型

c++ - 可以为数组分配初始化列表吗?

c++ - 数组中是否也可以动态删除内存?

c++ - 使用基类而不是基指针来处理派生类

sql - 具有继承性的 PostgreSQL 外键

javascript - 重用在 Controller 之间定义的功能

c++ - QGraphicsWidget 作为 QObject 的 child

c++ - 如何在 C++ 中调用::CreateProcess 来启动 Windows 可执行文件?

python - 禁用类实例化的最佳实践