在C++中,我不能在不分离标头和 cpp 的情况下实现此类吗?
In C++, Can't I implement this classes without separating header and cpp?
假设我有"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
,而无需为A
和B
提供单独的翻译单元,也不必分离A
和B
的接口和实现?
您可以这样做 - 但您仍然需要遵循前向申报的规则:
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;
}
相关文章:
- 在没有未定义行为的情况下实现类似std::vector的容器
- C++标准是否允许<double>在没有开销的情况下实现 std::可选
- 如何在编译器C++不智能的情况下实现 GLSL vec* 构造语法?
- 在不创建新节点的情况下实现带有映射的trie
- 如何在不停滞主循环的情况下实现对话系统?
- 如何在不引入未来对象切片的情况下实现 ICloneable
- 如何在没有参数的情况下实现返回双向链表大小的函数?int size() const.
- 在C++中,我不能在不分离标头和 cpp 的情况下实现此类吗?
- 如何在不修改C 中的LHS参数的情况下实现` `运算符
- 如何在不使用 lambda 表达式的情况下实现特定的比较器
- 如何在不必绑定到特定类的情况下实现观察者模式
- 是否可以在没有类型推断的情况下实现类似转发引用的行为
- 如何在不弄乱库 API 的情况下实现条件编译?
- 如何在没有这个运算符的情况下实现默认运算符<<(ostream&,T)的类型?
- 如何在无法访问 vblank 的情况下实现平均 60(或 30,或其他数字)FPS?
- 如何在不使用指针的情况下实现引用中的链表
- 如何在不使用指针的情况下实现链表
- 在没有虚拟关键字的情况下实现虚拟函数
- 如何在没有重复代码的情况下实现"const"和"non-const"重载?
- 为什么大小..(T)这么慢?在没有大小的情况下实现C++14 make_index_sequence.(T)