C++ typedef枚举的重新定义
例如,我们有以下源文件: 类型.h:C++ typedef枚举的重新定义,c++,types,enums,typedef,C++,Types,Enums,Typedef,例如,我们有以下源文件: 类型.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 colo
#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( ... );
从whatever.h是一个myColorSet
的声明。我想在getColor
函数中使用myColorSet
作为返回类型。我错过什么了吗
另外,当我在whater.h(而不是whater.cpp)中包含“types.h”时,效果很好。但据我所知,最好避免在.h文件中包含
我应该把include放在where.h中,还是有其他(对吗?)方法?谢谢。在which.h中,您需要
#include "types.h"
或者如果没有,编译器将无法识别该类型,即使该类型已在whater.cpp中用whater.h声明;错误发生在任何地方
另一种解决方案是去掉types.h,将其
typedef
放在whatever.h中,并从whatever.cpp中删除#include“types.h”
,这意味着您必须在whatever.cpp中执行#include“types.h”
,并且意味着您将有更少的文件要包含[更容易记住]当您声明myColorSet getColor(int args[])
时,编译器还不知道myColorSet
;但它需要这样做,因为myColorSet
是该函数的返回类型
您是对的,最好避免将其包含在.h文件中。但这仅适用于必须在#include
和转发声明之间进行选择的情况。在这种情况下,最好采用远期声明。有些情况下,远期申报是不够的。在这些情况下,您必须使用#include
您可以通过which.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
}
但不建议这样做,因为现在编译取决于包含标题的顺序。您不在
whatever.h中包含类型.h
,因为?不要使头文件基于包含在其中的.cpp文件而依赖于链。这是一个可怕的习惯。which.h
的使用者希望它能为翻译单元带来所需的东西。无论是谁告诉你“最好不要包含在.h文件中”,都应该放在你的“不要听他们”列表中。非常好的解释以及你关于包含顺序的建议,这很幸运地解释了为什么我几乎可以肯定,如果我在whater.cpp中包含一些内容,编译器会知道它使用了whater.hx)谢谢你,好心的先生。