头部保护难题 - 已经在.obj问题中定义 [英] header guard conundrum - already defined in .obj problem
问题描述
我有一个类(A),它必须包括两个文件,类X和类Y.不幸的是,类Y也需要在它的头文件中包含类X,因为构造函数接受一个类X类型的指针作为参数。
潜在的问题是会出现链接器错误?因为类A现在有两个类X的副本,它需要使用它,一个从类Y.这是头保护没有用的情况。我的问题是 - 这是纯粹的结构性问题还是有办法解决这个问题?
我真的不喜欢在类Y的头文件中包含任何东西,想要包括其他任何东西,但它是必要的,因为函数原型?
如果您有以下信息:
Xh
#ifndef X_H__
#define X_H__
class X
{
public:
int foo(){return 1; }
};
#endif
Yh >
#ifndef Y_H__
#define Y_H__
#includeXh
class Y
{
public:
Y(X * pX){myval = pX-> foo(); }
int myval;
};
#endif
something.cpp / p>
#includeXh
...
something_else.cpp
#includeYh
...
但是,如果
Xh
改为:#ifndef X_H__
#define X_H__
class X
{
public:
int foo();
};
int X :: foo(){return 1; }
#endif
尝试链接
something.cpp
和something_else.cpp
。X :: foo
将被非内联定义为两个单独的翻译单元。I have a class (A) which has to include two files, class X and class Y. unfortunately class Y also needs to include class X in it's header file because the constructor takes a pointer to a class X type as an argument.
The potential problem is that there would be a linker error? as class A now has two copies of class X in it, one that it needs to use, and one from class Y. This is the situation where header guards are of no use. My question is - is this purely a structural problem or is there a way around this?
I really would prefer to not include anything in class Y's header file, in case I want to include THAT in anything else, but is it necessary because of the function prototype?
解决方案If you have the following:
X.h
#ifndef X_H__ #define X_H__ class X { public: int foo() { return 1; } }; #endif
Y.h
#ifndef Y_H__ #define Y_H__ #include "X.h" class Y { public: Y(X *pX) { myval = pX->foo(); } int myval; }; #endif
something.cpp
#include "X.h" ...
something_else.cpp
#include "Y.h" ...
Then there should be no problem.
However, if
X.h
instead looks like this:#ifndef X_H__ #define X_H__ class X { public: int foo(); }; int X::foo() { return 1; } #endif
then you will indeed get a linker error when you try to link
something.cpp
andsomething_else.cpp
.X::foo
will have been defined non-inline into two separate translation units.这篇关于头部保护难题 - 已经在.obj问题中定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!