【发布时间】:2019-11-03 05:13:55
【问题描述】:
有人可以解释为什么我在构建过程中收到语法错误:标识符“Bar”,而foo.hpp 头文件中没有包含class Bar;?
在构建之前,我在 Visual Studio 2019 中没有收到任何错误,构建顺序似乎是 bar,然后是 foo,然后是 main,因此遵循 #include 语句看起来好像在构建过程中,bar 头文件首先包含在 foo 头中。
我在下面包含了概述基本问题的代码。
//Foo header file
#pragma once
#include "bar.hpp"
#include <iostream>
class Bar; //Commenting this line out results in no longer being able to build the project
class Foo {
public:
Foo();
void pickSomething(Bar& bar);
};
//Foo cpp file
#include "foo.hpp"
Foo::Foo() {
std::cout << "Made Foo" << std::endl;
}
void Foo::pickSomething(Bar& bar) {
bar.getSomething();
std::cout << "Picked something!" << std::endl;
}
//Bar header file
#pragma once
#include "foo.hpp"
#include <iostream>
class Foo;
class Bar {
public:
Bar(Foo& foo);
void getSomething();
};
//Bar cpp file
#include "bar.hpp"
Bar::Bar(Foo& foo) {
std::cout << "Made bar" << std::endl;
}
void Bar::getSomething() {
std::cout << "Gave something!" << std::endl;
}
//main file
#include "foo.hpp"
#include "bar.hpp"
int main() {
Foo foo;
Bar bar(foo);
foo.pickSomething(bar);
return 0;
}
【问题讨论】:
-
您是否在构建期间收到这些错误,或者它们在代码侧边栏中突出显示?
-
我只在构建期间收到它们。
-
看来你有一个循环包含。如果 file2 包含 file1,则 file1 不能包含 file2。
-
假设这两个类以原始代码的方式相互依赖,那么组织文件的正确方法是什么? foo 和 bar 是否应该在单个标题中定义?不知何故,这感觉像是一种糟糕的做法。
-
参见this answer 以了解非常相似的案例。