正如这篇答案所建议的那样,我知道在函数声明中允许使用不完整类型作为返回值。所以我写了以下代码:
Obj.h
class Obj {
int x;
};
f.h
class Obj;
Obj f();
f.cpp
#include "Obj.h"
Obj f() {
return Obj();
}
main.cpp
#include "f.h"
int main() {
f();
return 0;
};
使用以下编译命令:
g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)
编译此代码。
g++ *.cpp
显示以下错误:
main.cpp: In function 'int main()':
main.cpp:4:7: error: invalid use of incomplete type 'class Obj'
f();
^
f.h:1:7: error: forward declaration of 'class Obj'
class Obj;
^
编译器不允许在函数声明中使用不完整类型作为返回值。这是为什么呢?