两个类和内联函数
我有两个类,它们都使用了其他一些类,例如:
// class1.h
class Class1;
#include "class2.h"
class Class1 {
public:
static Class2 *C2;
...
};
// class2.h
class Class2;
#include "class1.h"
class Class2 {
public:
static Class1 *C1;
...
};
当我像上面的示例中那样定义它时,它就可以工作(我还有一些 #ifndef
来避免无限的标头重复) 。但我还想向我的类添加一些内联函数。我读到这里我应该放置内联函数的定义在头文件中,因为如果我将它们放入 cpp 文件并想从其他 cpp 文件调用它们(当我这样做时,我在链接期间得到未定义的引用),它将不起作用。但这里的问题是这样的:
// class1.h
...
inline void Class1::Foo() {
C2->Bar();
}
我收到错误:无效使用不完整类型“struct Class2”。
那么我该怎么做呢?
I have two classes and both of them uses some of the other class, on example:
// class1.h
class Class1;
#include "class2.h"
class Class1 {
public:
static Class2 *C2;
...
};
// class2.h
class Class2;
#include "class1.h"
class Class2 {
public:
static Class1 *C1;
...
};
And when I define it like in example above, it works (I also have some #ifndef
to avoid infinite header recurency). But I also want to add some inline functions to my classes. And I read here that I should put definition of inline function in header file, because it won't work if I'll put them in cpp file and want to call them from other cpp file (when I do it I get undefined reference during linking). But the problem here is with something like this:
// class1.h
...
inline void Class1::Foo() {
C2->Bar();
}
I get error: invalid use of incomplete type ‘struct Class2’.
So how can I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要延迟包含标头,但随后包含它并定义内联方法。通过在每个标头中执行此操作,它们是自给自足的,并且包含一个将始终包含另一个,并且 包含防护 防止无限递归。
A.hpp
B.hpp
You need to delay including the header, but then include it and define your inline methods. By doing this in each header, they are self-sufficient and including one will always include the other, with include guards preventing infinite recursion.
A.hpp
B.hpp
你把它搞混了。您想要的是:
并在源代码中包含相应的标题。该行:
声明一个不完整类型,并且您可以拥有对不完整类型的指针和引用。但在使用时,它需要完整。所以只要说“嘿它会存在!”在标题中,并在源代码中告诉它它是什么。
You have it mix'd up. What you want is:
And include the respective headers in the source. The line:
Declares an incomplete type, and you can have pointers and references to incomplete types. Upon usage, though, it needs to be complete. So just say "hey it'll exist!" in the header, and in the source tell it what it is.
我的建议是,将通用方法和成员放入基类中,然后从基类派生 C1 和 C2。这可能会解决循环依赖问题。
My suggestion is that you place common methods and members into a base class, then derive C1 and C2 from the base class. This may fix the circular dependency issue.