使用单元测试 (cppunit) 中另一个文件中定义的结构时出错

Error using struct defined in another file in UnitTesting (cppunit)

本文关键字:定义 结构 出错 文件 另一个 单元测试 cppunit      更新时间:2023-10-16

我有一个Parser.h,它定义了一个结构StmtParent

...
struct StmtParent;
class Parser {
...

然后在Parser.cpp

struct StmtParent {
int stmtNo;
int parent;
};
... 

好像没事吧?然后我有一个单元测试(cppunit):

# in ParserUnitTests.h
#include "headerParser.h"
# in ParserUnitTests.cpp
void ParserUnitTests::testParseProcSideEffects() {
...
stack<StmtParent> follows;
...

然后我收到这样的错误:

error C2027: use of undefined type 'StmtParent'

为什么,我可以使用像Parser::parseLine()这样的函数。为什么我无法访问结构?所以我尝试在ParserUnitTests.cpp中包含Parser.h(尽管我已经将其包含在标题中)。然后我得到:

Error   8   error C2146: syntax error : missing ';' before identifier 'm_cCurToken' c:program files (x86)microsoft sdkswindowsv7.0aincludeparser.h    52
Error   9   error C4430: missing type specifier - int assumed. Note: C++ does not support default-int   c:program files (x86)microsoft sdkswindowsv7.0aincludeparser.h    52
Error   10  error C4430: missing type specifier - int assumed. Note: C++ does not support default-int   c:program files (x86)microsoft sdkswindowsv7.0aincludeparser.h    52
...
Parser.h

不定义结构,而是向前声明它。因此,当您尝试将其用作stack的模板参数时,它是不完整的,并且不能将不完整的类型用作 STL 容器的参数:

C++11草案3035,17.4.3.6,第2款:

具体而言,在以下情况下未定义效果:

如果在实例化模板组件时将不完整的类型 (3.9) 用作模板参数, 除非该组件特别允许。

你可以看看这个推理。