由于answer暗示,我知道允许在函数声明中使用不完整的类型作为返回值。所以我写了下面的代码:函数返回类型的前向声明
Obj.h
class Obj {
int x;
};
f.h
class Obj;
Obj f();
f.cpp
#include "Obj.h"
Obj f() {
return Obj();
}
使用以下编译命令
g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)
:的main.cpp
#include "f.h"
int main() {
f();
return 0;
};
编译此代码与以下编译器
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;
^
因此,编译器不允许在函数声明中使用不完整类型作为返回值。什么解释?
您是否将f.cpp和main.cpp编译在一起? – NathanOliver
@NathanOliver我编辑了编译命令。是的,我将它们编译在一起 –