【问题标题】:classes depend on each other类相互依赖
【发布时间】:2012-09-06 01:28:22
【问题描述】:

考虑这些 c++ 片段:

foo.h:

class foo
{
bar myobj;
};

bar.h:

class bar
{
foo *yourobj;
};

其他文件:

#include "foo.h" //because foo.h is included first bar will not be defined in foo.h
#include "bar.h"

foo container;

bar blah;

我知道我没有费心去写构造函数之类的东西,但你明白了。有谁知道解决这种情况的方法吗?

【问题讨论】:

  • 在继续之前,请尝试计算sizeof(foo)
  • 指针是您的解决方案。
  • 基本上他们的意思是,不可能在 bar 中同时有一个 foo 和一个 bar 在 foo 中,所以你需要重新考虑你真正想要什么。
  • 每个 foo 里面都有一个 bar。每个酒吧里都有一个 foo。哦哦。
  • 您可能需要重新考虑您的类模式,因为对象之间不应该相互需要,否则会造成无限的对象创建循环

标签: c++ oop class


【解决方案1】:

有几种常见的技术可以做到这一点。

首先,尽可能使用前向声明。 其次,如果循环依赖的一部分依赖于类中的函数,则使该类继承自提供这些函数声明的“接口”类。 最后,使用 PIMPL(指向实现细节的指针)。无需在类声明中列出所有字段,只需包含指向实际类数据的指针即可。

例如foo.h

class foo_members;

class foo
{
    foo_members* opaque;
};

foo.cpp

#include "bar.h"
class foo_members{
    bar mybar;
};

【讨论】:

  • foo_members 析构函数呢?我收到警告note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined
  • 找到了解决方案。必须在提供两个类实现之后定义析构函数。只需将析构函数定义移动到 .cpp 文件。
【解决方案2】:

另一种方法是只制作一个声明所有类的标头。

[classes.h]

class foo;
class bar;

class foo
{
    bar *FoosBar;
    int FooFunc(void);
};

class bar
{
    foo *BarsFoo;
    bool BarFunc(void);
}

[foo.cpp]

#include "classes.h"

int foo::FooFunc(void)
{
    // Reference FoosBar somewhere here or something maybe
    return 7;
}

[bar.cpp]

#include "classes.h"

bool bar::BarFunc(void)
{
    // Reference BarsFoo somewhere here or something maybe
    return true;
}

【讨论】:

  • 问题是我正在开发一个大型而复杂的软件,如果我开始这样做很容易变得混乱。
  • 是的,我明白你的意思,但循环依赖本身让我感到困惑。尝试使 classes.h 文件仅具有前向声明并且不定义类的任何成员class Foo; class Bar; 然后确保 Foo.h 和 Bar.h 都包含 classes.h,并且 Foo.cpp 包含 Bar.h , Bar.cpp 包括 Foo.h
猜你喜欢
  • 1970-01-01
  • 2011-09-18
  • 1970-01-01
  • 2013-09-03
  • 2011-04-26
  • 2017-05-09
  • 1970-01-01
  • 2013-10-21
  • 1970-01-01
相关资源
最近更新 更多