c – 转发声明的替代方案

c – 转发声明的替代方案,第1张

概述我注意到,将类或struct关键字预先添加到另外需要转发的类型的类型中,就像该类型被转发为已声明一样: // struct Test; forward declaration commentedvoid* foo(struct Test* t) // C style function parameter - This works !{ return t; } 我没有意识到这一点.我 我注意到,将类或struct关键字预先添加到另外需要转发的类型的类型中,就像该类型被转发为已声明一样:
// struct Test; forward declaration commentedvoID* foo(struct Test* t) // C style function parameter - This works !{    return t; }

我没有意识到这一点.我不知道它是标准的C还是扩展名,以及参数之前的struct关键字是作为前向声明还是另一个机制启动.

此外,在这样的使用之后,“下一个”功能可以使用该类型而不预先添加任何关键字:

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}

这将T和S作为类名称和foo作为函数名称引入命名空间矿.

注意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 – 转发声明的替代方案全部内容,希望文章能够帮你解决c – 转发声明的替代方案所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1251032.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存