c++ - 在 C++ 中,我不能在不分离 header 和 cpp 的情况下实现这些类吗?

标签 c++ class

假设我有“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.hpp

#ifndef _B_HPP_
#define _B_HPP_

#include "A.hpp"

class B {
public:
  A* a_;
  B() : {
    a_ = new A( *this );
  }

  void foo() {
  }
};

#endif

main.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 的接口(interface)和实现?

你可以这样做 - 但你仍然需要遵循转发声明的规则:

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;
}

关于c++ - 在 C++ 中,我不能在不分离 header 和 cpp 的情况下实现这些类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42897370/

相关文章:

c++ - g++ 对构造函数的 undefined reference

java - 在数组中存储变量?

C++虚拟类基础题

java - 按层次结构对类进行排序的树

c++ - 在 C++ 中从 'char' 到 'const Char*' 的无效转换

c++ - 我是否需要对 K 类进行完整排序才能使用 std::map<K, L>

c++ - 在 C++ 中经过 30 毫秒后退出循环的最佳方法是什么

c++ - '*(<type> *) &x' 和 'x' 有什么区别?

ruby - Rspec Array_extensions 类或实例方法

python - 错误说明 - 'statInter' 对象没有属性 'tk'