且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不允许嵌套函数,但为什么允许嵌套函数原型? [C ++]

更新时间:2023-11-09 19:39:22

您的原型只是「转寄声明」。请检查***文章。

Your prototype is just 'Forward Declaration'. Please check out the Wikipedia article.

基本上,它告诉编译器如果标签SomeFun以这种方式使用,不要担心。 但是你的链接器负责找到正确的函数体。

Basically, it tells the compiler "don't be alarmed if the label 'SomeFun' is used in this way". But your linker is what's responsible for finding the correct function body.

你可以声明一个伪造的原型,例如'char SomeFun()'并使用它在你的主。当你的链接器试图找到你的虚假函数的主体时你只会得到一个错误。但你的编译器会很酷的。

You can actually declare a bogus prototype, e.g. 'char SomeFun()' and use it all over your main. You will only get an error when your linker tries to find the body of your bogus function. But your compiler will be cool with it.

有很多好处。你必须记住函数体并不总是在同一个源代码文件中。它可以在一个链接库。此外,该链接库可能有一个特定的链接签名。使用条件定义你甚至可以选择正确的链接签名在构建时使用您的作用域原型。虽然大多数人会使用函数指针

There are lots of benefits. You have to remember the function body is not always in the same source code file. It can be in a linked library.Also, that linked library may be have a specific 'link signature'.Use conditional defines you may even select the correct link signature at build time using your scoped prototypes.Although most people would use function pointers for that instead.

希望这有帮助。