【发布时间】:2017-03-08 12:12:44
【问题描述】:
我将在utilA.cpp中有如下代码sn-p:
// utilB.h
namespace xm
{
void zoo(struct tm timeval); //<-----line 0
}
// utilA.cpp
#include <utilB.h> //<----line 1
#include <time.h> //<----line 2
namespace xm
{
void foo()
{
struct tm time1 = {0}; //<----line 3
}
}
编译utilA.cpp时GCC报错,
error: variable 'xm::tm time1' has initializer but incomplete type
这似乎是因为utilA.h在第0行使用struct tm,但没有包含time.h,编译器将第0行的struct tm视为前向声明,所以struct tm在第 2 行被解析为 xm::tm 在第 0 行的标题内。
那么 C++ 标准是否将 struct tm 定义为一种函数参数类型作为前向声明?请帮助解释这一点,标准中的引用会有所帮助。
【问题讨论】:
-
在标题中写入
#include <time.h>,因为您的标题依赖于它。 -
是的,我们应该在utilB.h中添加#include
,但是因为这是来自一个巨大项目的代码sn-p,在我们找到根本原因之前它让我们很困惑。 -
这是一种非常糟糕的编程风格。忽略它。 PS:有没有试过把
#include-s 移到顶部? -
@molbdnilo 他们不需要
tm的定义来声明zoo。除非你的意思是说你不能前向声明标准库类型,在这种情况下你是对的 -
@krzaq 不,但每次使用
zoo都需要定义。拥有独立的标题是一种很好的形式。
标签: c++ language-lawyer standards forward-declaration