c++ - 返回但不使用类型的 C++ 函数是否需要 #include 该类型?

标签 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/

相关文章:

c++ - 调用构造函数重新初始化变量似乎不起作用?

c++ - C++中的strchr如何保证其调用者不会修改作为参数传递的字符串

c++ - 将变量添加到已在 C++ 中声明的数组?

C++ 使用 'this' 作为参数

c++ - 为什么我的 C++ 异常没有被捕获?

c++ - 检测堆损坏

c++ - 引用是否改变了引用对象的状态

c++ - 关于 C++ (UNIX) 中的套接字连接超时

c++ - 将 void 指针类型转换为 int 时出现段错误

c++ - HBITMAP hbm = LoadImage函数返回NULL