c++ - 前向声明的替代方案

标签 c++

我注意到,classstruct 关键字添加到一个需要前向声明的类型上 就好像该类型是前向的一样声明:

// struct Test; forward declaration commented

void* foo(struct Test* t) // C style function parameter - This works !
{
    return t; 
}

我没有意识到这一点。我想知道它是标准 C++ 还是扩展,以及参数之前的 struct 关键字是否用作前向声明或其他机制。

此外,在这样的用法之后,“next”函数可以使用该类型而无需预先添加任何关键字:

void* oof(Test* t);

Demo

最佳答案

这是合法的,但可能不是一个好主意。

来自[basic.scope.pdecl]/6:

[...] — for an elaborated-type-specifier of the form
class-key identifier
if the elaborated-type-specifier is used in the decl-specifier-seq or parameter-declaration-clause of a function defined in namespace scope, the identifier is declared as a class-name in the namespace that contains the declaration [...]

例如:

namespace mine {
    struct T* foo(struct S *);
//  ^^^^^^^^^---------------- decl-specifier-seq
//                ^^^^^^^^^^--- parameter-declaration-clause
}

这将 TS 作为类名和 foo 作为函数名引入 namespace mine


请注意,C 中的行为不同;结构名称仅在函数范围内有效。

6.2.1 Scopes of identifiers

4 - [...] If the declarator or type specifier that declares the identifier appears [...] within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the end of the associated block. If the declarator or type specifier that declares the identifier appears within the list of parameter declarations in a function prototype (not part of a function definition), the identifier has function prototype scope, which terminates at the end of the function declarator.

gcc 对 C 代码中的这种用法给出了适当的警告:

a.c:3:18: warning: ‘struct Test’ declared inside parameter list
 void* foo(struct Test* t)
                  ^
a.c:3:18: warning: its scope is only this definition or declaration, which is probably not what you want

关于c++ - 前向声明的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31696292/

相关文章:

c++ - 为什么在 C++ 中允许重新声明模板成员函数?

c++ - 如何在Qt中播放QByteArray中的声音

c++ - Qt。将项目从 Linux 移动到 Windows。为什么 Qt creator 返回错误 c1083 can't open directory or file?

c++ - 添加子子节点以 boost ptree

c++ - UINT64 不是 boost 的成员

c++ - 使用 boost shared_ptr

c++ - C++11 theads 的最基本并行化失败

c++ - 从 C++ 调用带有可选参数的 Fortran 子例程

android - 运行 OpenCV 混合处理教程时出现 UnsatisfiedLinkError

c++ - 如何在目标makefile中设置多个变量