[英]Cross dependencies without forward declaring all used functions?
I have class A (in Ah) which depends on class B in (Bh) and vice versa. 我有A级(在Ah中),它取决于(Bh)中的B类,反之亦然。 Forward declaring the used functions works, but this means I have to update everywhere where I forward declared those functions in the future, ex, if I remove, or change argument in those functions they must all be updated to reflect change.
前向声明使用的函数有效,但这意味着我必须更新我前面声明这些函数的所有地方,例如,如果我删除,或者更改这些函数中的参数,它们必须全部更新以反映更改。 I don't feel this is good practice.
我觉得这不是好习惯。 Is there a way around this?
有没有解决的办法?
Thanks 谢谢
If you only need to work with pointers or references to a class at the declaration level, you can do it like this: 如果您只需要在声明级别使用指针或类的引用 ,您可以这样做:
class B; // forward class declaration
class A {
A(B &);
};
class A;
class B {
B(A &);
};
#include "B.h"
#include "A.h" // now we get the full declaration of A
B::B(A &a) {
a.foo(5);
}
Mutual dependencies like this are tough to deal with but sometimes unavoidable. 像这样的相互依赖很难处理,但有时是不可避免的。
If A
and B
depend on the implementations of each other, then you've got a system design problem that you need to resolve before proceeding further. 如果
A
和B
依赖于彼此的实现 ,那么在进一步操作之前,您需要解决系统设计问题。
The best way is to have a forward declaration header: 最好的方法是有一个前向声明标题:
a.fwd.h a.fwd.h
#pragma once
class A;
ah 啊
#pragma once
#include "a.fwd.h"
#include "b.fwd.h"
class A
{
A(B*);
};
etc. 等等
This way, each class provides its own forward declarations - localised alongside the header where it belongs - checked for consistency with the real declarations and definitions by including the forward declaration header in the header, and the header in the implementation. 这样,每个类提供自己的前向声明 - 与它所属的头一起定位 - 通过在头中包含前向声明头和实现中的头来检查与真实声明和定义的一致性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.