假设我有“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
而不需要为A
和B
单独的翻译单元,并且无需分离 A
和 B
的接口(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/