【问题标题】:C++ Simple circular reference and forward declaration issueC++ 简单循环引用和前向声明问题
【发布时间】:2017-02-08 11:31:13
【问题描述】:

我收到此错误:

错误 C3646:“bar”:未知覆盖说明符

尝试在 Visual Studio 2015 中编译这个非常简单的 C++ 代码时:

ma​​in.cpp

#include "Foo.h"

int main ()
{
    return 0;
}

Foo.h

#pragma once

#include "Bar.h"

class Foo
{
public:
    Foo();

    Bar bar;
};

Bar.h

#pragma once

#include "Foo.h"

class Bar
{
public:
    Bar();
};

我知道有一个循环引用,因为每个 .h 都包含另一个,并且解决方案应该使用 前向声明,但它们似乎不起作用,有人可以解释为什么吗?我在这里发现了类似的问题,并且解决方案总是相同的,我想我错过了一些东西:)

【问题讨论】:

  • 那么......你的前向声明在哪里?
  • 如果你想在Foo 之前使用Bar 的前向声明,那么Bar bar; 是一个错误,因为此时编译器应该知道Bar 的大小,但是你可以使用聚合:Bar* bar.

标签: c++ class visual-studio-2015 include forward-declaration


【解决方案1】:

循环引用完全是您自己制作的,您可以通过从 Bar.h 中删除 #include "Foo.h" 来安全地删除它:

#pragma once

//#include "Foo.h"  <---- not necessary, Bar does not depend on Foo

class Bar
{
public:
    Bar();
};

您不需要在Foo.h 中前向声明Bar。更一般的情况是,如果 FooBar 相互依赖,则需要前向声明。

【讨论】:

  • 当然可以,但我的意思是,如果它们相互依赖,你如何解决它?
  • @JoePerkins 这将是另一个问题的主题,但通常你可以让类具有彼此的指针,如下所示:class Foo; class Bar { Foo* f; }; class Foo { Bar* b; }; 但你不能拥有相互包含非指针成员的类其他。
  • 所以解决方案是用指针代替。我在学习 C++ 时完全错过了这些信息!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多