This question already has answers here:
Resolve build errors due to circular dependency amongst classes
                                
                                    (11个答案)
                                
                        
                                4年前关闭。
            
                    
为什么不能在Consumer中创建类Bor的实例?请看下面的简化示例。

##main.cpp
#include "Consumer.hpp"
#include "Bor.hpp"
int main(int argc, char** argv) {
    Bor bor;
    return 0;
}


这是消费者:

##consumer.cpp

#include "Consumer.hpp"
#include "Bor.hpp"
Consumer::Consumer(Bor& bor) :
bor(bor) {}
void Consumer::startConsumeLoop() {}


消费者标头:

##consumer.hpp

#ifndef CONSUMER
#define CONSUMER
#include "Bor.hpp"
class Consumer{
 public:
    Consumer(Bor& bor);
    void startConsumeLoop();
 private:
    Bor& bor;
};
#endif


这是Bor:

##Bor.cpp

#include "Bor.hpp"
#include "Consumer.hpp"
Bor::Bor(){}


BOR标头:

##Bor.hpp

#ifndef BOR
#define BOR
#include "Consumer.hpp"
class Bor{
 public:
    Bor();
};
#endif


这是我运行要编译的命令:

clang++ -std=c++11 Consumer.cpp Main.cpp Bor.cpp


和错误:

./Consumer.hpp:6:11: error: unknown type name 'Bor'
        Consumer(Bor& bor);
./Consumer.hpp:8:2: error: unknown type name 'Bor'
        Bor& bor;

最佳答案

Bor.hpp不应具有#include "Consumer.hpp"
Consumer.hpp可能只具有类Bor的前向声明,而不是include。

09-11 20:48