不允许嵌套函数,但为什么允许嵌套函数原型? [C ++] [英] Nested functions are not allowed but why nested function prototypes are allowed? [C++]

查看:253
本文介绍了不允许嵌套函数,但为什么允许嵌套函数原型? [C ++]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是阅读链接的问题,让我提出这个问题。

I was reading the linked question which leads me to ask this question.

请考虑下列代码

int main()
{
    string SomeString();
}



所有说,编译器将此作为函数原型,而不是 string 对象。现在考虑下面的代码。

All says, compiler takes this as a function prototype and not as a string object. Now consider the following code.

int main()
{
    string Some()
    {
        return "";
    }
}

编译器说这是无效的,因为我猜嵌套函数定义不允许。 如果不允许,为什么允许嵌套的函数原型?它不是给任何优势,而不是混淆(或我在这里缺少一些有效的点?)。

Compiler said this is invalid as I guess nested function definition is not allowed. If it is not allowed, why nested function prototypes are allowed? It is not giving any advantage rather than making confusion (or am I missing some valid points here?).

我想出以下是有效的。

int main()
{ 
  string SomeFun();
  SomeFun();
  return 0;
}

string SomeFun()
{
  std::cout << "WOW this is unexpected" << std::endl;
}

这也令人迷惑。我期望函数 SomeFun()将只在 main 中有一个范围。但我错了。为什么编译器允许编译像上面的代码?

This is also confusing. I was expecting the function SomeFun() will have a scope only in main. But I was wrong. Why compiler is allowing to compile code like the above? Is there any real time situations where code like the above makes sense?

有什么想法吗?

推荐答案

您的原型只是转发声明。请检查维基百科文章。

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.

希望这有帮助。

这篇关于不允许嵌套函数,但为什么允许嵌套函数原型? [C ++]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆