例如,我们有以下源文件:
types.h:
#pragma once
typedef enum { RED, GREEN, BLUE } myColorSet;
随便什么:h:
#pragma once
myColorSet getColor( int args[] );
随便.cpp
#include "whatever.h"
#include "types.h"
myColorSet getColor( int args[] ) {
//returning the color according to args
}
编译抛出:
'myColorset':重新定义;符号不能使用typedef重载。请参见“ myColorset”的声明。
这对我来说有点令人困惑,但似乎编译器认为
myColorSet getColor( ... );
从what.h是。的声明myColorSet
。我想myColorSet
用作getColor
函数的返回类型。我想念什么吗?
另外,当我在what.h(而不是whatth.cpp)中包含“ types.h”时,它也可以正常工作。但据我所知,最好避免包含在.h文件中。
我应该只在include.h中添加include还是有另一种(对吗?)方法?谢谢你。
当您声明时myColorSet getColor( int args[] )
,编译器尚不知道myColorSet
;但这是必需的,因为它myColorSet
是该函数的返回类型。
没错,最好避免包含在.h文件中。但这仅适用于必须在#include
和向前声明之间进行选择的情况。在这种情况下,最好使用前向声明。在某些情况下,向前声明还不够。在这些情况下,您必须使用#include
。
您可以在不更改标题的情况下摆脱困境,whatever.cpp
例如
#include "types.h"
// myColorSet is now known, so we can declare getColor(int args[]) now:
#include "whatever.h"
myColorSet getColor( int args[] ) {
//returning the color according to args
}
但是不建议这样做,因为现在编译取决于头文件的包含顺序。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句