<分区>
此文件是否需要 #include
来定义 FooType
?函数的类型签名返回 FooType*
但函数实现不使用 FooType
。
// test.cpp
class FooType; // Unresolved forward declaration
FooType* GetFoo() { return nullptr; }
它使用 g++ --std=c++11 -Wall
在没有警告的情况下构建。那么这是前向声明的合法使用吗?
标签 c++
<分区>
此文件是否需要 #include
来定义 FooType
?函数的类型签名返回 FooType*
但函数实现不使用 FooType
。
// test.cpp
class FooType; // Unresolved forward declaration
FooType* GetFoo() { return nullptr; }
它使用 g++ --std=c++11 -Wall
在没有警告的情况下构建。那么这是前向声明的合法使用吗?
最佳答案
来自cppreference :
A declaration of the following form
class-key attr identifier ;
Declares a class type which will be defined later in this scope. Until the definition appears, this class name has incomplete type.
...
and if a particular source file only uses pointers and references to the class, this makes it possible to reduce #include dependencies.
所以这个语法是完全有效的,因为你使用了一个指针Foo*
。
关于c++ - 返回但不使用类型的 C++ 函数是否需要 #include 该类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39800527/