C++ 简单循环引用和前向声明问题

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

我收到此错误:

error C3646: 'bar': unknown override specifier

当尝试在 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 都包含另一个,解决方案应该使用前向声明,但它们似乎不起作用,有人可以解释为什么吗?我在这里发现了类似的问题,并且解决方案总是相同的,我想我错过了一些东西:)

最佳答案

循环引用完全是您自己造成的,您可以通过从 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 相互依赖,则需要前向声明。

关于C++ 简单循环引用和前向声明问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42111943/

相关文章:

c++ - 如何在 OCCI setDataBuffer 中使用 vector<string>?

c++ - 分数运算符

java - 使用终端从文件夹 Mac 运行 Java 程序

c - Windows C套接字: select() gives WSAENOTSOCK error

VS2015 中的 SharePoint 2016 模板

c++ - ToString<T> 好的做法?

c++ - vc++ - 如何将 CString 转换为 LPCWSTR

c++ - gcc编译的二进制文件大小不同?

python - 在 Python 中使用变量创建类的实例

c# - Visual Studio 2015 的 AllMargins