您可能在单个翻译单元中多次包含此头文件。当文件第二次包含时,struct udtCharVec
已经被定义,所以你会得到一个“类型重定义”的错误。
添加include guard。第一包含后,CharVec_H
将被定义,所以文件的其余部分将被忽略:
#ifndef CharVec_H
#define CharVec_H
#include "stdafx.h"
#include <string>
using namespace std
struct udtCharVec
{
wstring GraphemeM3;
wstring GraphemeM2;
};
#endif
说你的项目包括三个文件。两个头文件和一个源文件:
CharVec.h
#include "stdafx.h"
#include <string>
using namespace std
struct udtCharVec
{
wstring GraphemeM3;
wstring GraphemeM2;
};
CharMatrix.h
#include "CharVec.h"
struct udtCharMatrix
{
CharVec vec[4];
};
的main.cpp
#include "CharVec.h"
#include "CharMatrix.h"
int main() {
udtCharMatrix matrix = {};
CharVec vec = matrix.vec[2];
};
预处理器已经运行后,主。 CPP看起来像这样(忽略标准库包括):
//#include "CharVec.h":
#include "stdafx.h"
#include <string>
using namespace std
struct udtCharVec //!!First definition!!
{
wstring GraphemeM3;
wstring GraphemeM2;
};
//#include "CharMatrix.h":
//#include "CharVec.h":
#include "stdafx.h"
#include <string>
using namespace std
struct udtCharVec //!!Second definition!!
{
wstring GraphemeM3;
wstring GraphemeM2;
};
struct udtCharMatrix
{
CharVec vec[4];
};
int main() {
udtCharMatrix matrix = {};
CharVec vec = matrix.vec[2];
};
此扩展文件包含struct udtCharVec
的两个定义。如果您将一个包含警卫添加到CharVec.h
,则第二个定义将被预处理器删除。
你在你定义struct的当前文件中有错误?或者你是否使用此代码作为其他文件的包含文件? – Dineshkumar
除了你的问题,不要在头文件中使用“using directive”:http://stackoverflow.com/questions/4872373/why-is-including-using-namespace-into-a-header-file- a-bad-idea-in-c –
其中是头文件的使用代码?编辑您的问题并发布... – pinkpanther