在C++中,我不能在不分离标头和 cpp 的情况下实现此类吗?

In C++, Can't I implement this classes without separating header and cpp?

本文关键字:情况下 实现 cpp C++ 不能 不分离      更新时间:2023-10-16

假设我有"A.hpp","B.hpp"和"main.cpp"。

A.hpp

#ifndef _A_HPP_
#define _A_HPP_
#include "B.hpp"
class A {
public:
  B& b_;
  A(B& b) : b_(b) {
  }
  void foo() {
     b_.foo();
  }
};
#endif

B.马力

#ifndef _B_HPP_
#define _B_HPP_
#include "A.hpp"
class B {
public:
  A* a_;
  B() : {
    a_ = new A( *this );
  }
  void foo() {
  }
};
#endif

主.cpp

#include "B.hpp"
#include "A.hpp"
int main()
{
   B b;
   b.a->foo();
   return 0;
}

我知道为什么我不能编译main.cpp但不知道如何在不分离A类和B类的头文件和源文件的情况下解决此问题(例如,A类和B类正在使用模板(

提前谢谢。 :)

如果我理解正确的话 - 您希望能够编译main.cpp,而无需为AB提供单独的翻译单元,也不必分离AB的接口和实现?

您可以这样做 - 但您仍然需要遵循前向申报的规则:

class B; // class `B` forward-declaration
// define class A, but don't implement the parts that need B's definition
class A {
public:
    B& b_; // `A` can use `B` here, but the compiler still doesn't know how B is defined
    A(B&& b); // also need to define A's structure, but not the method implementations
    void foo(); 
};
class B {
public:
    A* a_;
    B() : {
        a_ = new A( *this );
    }
    void foo() { }
};
// now we can define `A` using the `A::` syntax, instead of class{}:
A::A(B&& b) : b_(b) { }
void A::foo() { b_.foo(); }
int main()
{
   B b;
   b.a->foo();
   return 0;
}