循环依赖? [英] Circular Dependencies?

查看:186
本文介绍了循环依赖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我理解转发声明,但在这种情况下,我需要调用BOTH的成员/字段结束,所以我不能使用。我试图覆盖.cpp文件中的声明(通过包含我需要使用的类的实际头),但是我在头部通过forward声明定义的指针被破坏时,我试图使用它。



我如何解决这个问题?你需要代码吗?

解决方案

你需要记住,形成指向类的指针只需要一个 因此,为了解决循环依赖,你可以这样做:



A.hpp

  B类; 

class A
{
public:
int foo(B * b);
int bar();
};

B.hpp

  A类; 

class B
{
A * m_a;
public:
int foo();
explicit B(A * a):m_a(a){}
};

A.cpp

  #includeA.hpp
#includeB.hpp

int A :: foo(B * b)
{
return 2 * b-> foo();
}

int A :: bar()
{
return 42;
$ b

  #includeA.hpp
#includeB.hpp

int B :: foo )
{
return m_a-> bar();
}


Okay, I understand forward declarations, but I need to call members / fields on BOTH ends in this case, so I can't use that. I tried to overwrite the declaration inside the .cpp file (by including the actual header of the class I need to use) but the pointer I defined in the header via forward declaration was broken when I tried to use it.

How can I get around this? Do you need code ?

解决方案

You need to keep in mind that forming a pointer to a class only requires a declaration of that class, while accessing that class's members requires its definition. So to solve circular dependencies, you can do this:

A.hpp

class B;

class A
{
public:
  int foo(B *b);
  int bar();
};

B.hpp

class A;

class B
{
  A *m_a;
public:
  int foo();
  explicit B(A *a) : m_a(a) {}
};

A.cpp

#include "A.hpp"
#include "B.hpp"

int A::foo(B *b)
{
  return 2 * b->foo();
}

int A::bar()
{
  return 42;
}

B.cpp

#include "A.hpp"
#include "B.hpp"

int B::foo()
{
  return m_a->bar();
}

这篇关于循环依赖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆