我收到此错误:
error C3646: 'bar': unknown override specifier
当尝试在 Visual Studio 2015 中编译这个非常简单的 C++ 代码时:
main.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
。更一般的情况是,如果 Foo
和 Bar
相互依赖,则需要前向声明。
关于C++ 简单循环引用和前向声明问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42111943/