两个类和内联函数 [英] Two classes and inline functions
问题描述
我有两个类,并且两个类都使用其他类,例如:
// class1.h
class Class1;
#includeclass2.h
class Class1 {
public:
static Class2 * C2;
...
};
// class2.h
class Class2;
#includeclass1.h
class Class2 {
public:
static Class1 * C1;
...
};
当我像上面的例子中定义它,它工作(我也有一些 #ifndef
以避免无限头recurency)。但我也想添加一些内联函数到我的类。我阅读了这里,我应该把内联函数的定义在头文件中,因为如果我将它们放在cpp文件,并希望从其他cpp文件(当我这样做,我得到未定义的引用链接期间)调用它不会工作。但这里的问题是这样的:
// class1.h
...
inline void Class1 :: Foo(){
C2-> Bar();
}
我得到错误:无效使用不完整的类'struct Class2' p>
那么我该如何做呢?
头文件,然后包括它,并定义你的内联方法。通过在每个标题中执行此操作,它们是自给自足的,并且包括一个将始终包括另一个,其中包含包含警卫防止无限递归。
A.hpp
#ifndef INCLUDE_GUARD_B9392DB18D114C1B8DFFF9B6052DBDBD
#define INCLUDE_GUARD_B9392DB18D114C1B8DFFF9B6052DBDBD
struct B;
struct A {
B * p;
void foo();
};
#includeB.hpp
inline
void A :: foo(){
if(p)p-> bar );
}
#endif
B.hpp
#ifndef INCLUDE_GUARD_C81A5FEA876A4C6B953D1EB7A88A27C8
#define INCLUDE_GUARD_C81A5FEA876A4C6B953D1EB7A88A27C8
struct A;
struct B {
A * p;
void bar();
};
#includeA.hpp
inline
void B :: bar(){
if(p)p-> foo );
}
#endif
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?
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
#ifndef INCLUDE_GUARD_B9392DB18D114C1B8DFFF9B6052DBDBD
#define INCLUDE_GUARD_B9392DB18D114C1B8DFFF9B6052DBDBD
struct B;
struct A {
B* p;
void foo();
};
#include "B.hpp"
inline
void A::foo() {
if (p) p->bar();
}
#endif
B.hpp
#ifndef INCLUDE_GUARD_C81A5FEA876A4C6B953D1EB7A88A27C8
#define INCLUDE_GUARD_C81A5FEA876A4C6B953D1EB7A88A27C8
struct A;
struct B {
A* p;
void bar();
};
#include "A.hpp"
inline
void B::bar() {
if (p) p->foo();
}
#endif
这篇关于两个类和内联函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!