不允许嵌套函数,但为什么允许嵌套函数原型?[C++]
我正在阅读链接的问题,这让我提出了这个问题.
考虑下面的代码
int main(){字符串 SomeString();}
总而言之,编译器将其作为函数原型而不是字符串对象.现在考虑以下代码.
int main(){字符串一些(){返回 "";}}
编译器说这是无效的,因为我猜不允许嵌套函数定义.如果不允许,为什么允许嵌套函数原型?它没有提供任何优势而不是制造混乱(或者我在这里遗漏了一些有效点?).
我发现以下是有效的.
int main(){字符串 SomeFun();一些乐趣();返回0;}字符串 SomeFun(){std::cout <<哇,这出乎意料"<<std::endl;}
这也令人困惑.我期望函数 SomeFun() 将只在 main 中具有作用域.但是我错了.为什么编译器允许编译上述代码?是否有任何实时情况使上述代码有意义?
有什么想法吗?
解决方案你的原型只是'前向声明'.请查看维基百科文章.
基本上,它告诉编译器如果以这种方式使用标签‘SomeFun’,请不要惊慌".但是您的链接器负责找到正确的函数体.>
您实际上可以声明一个伪造的原型,例如'char SomeFun()' 并在您的主要内容中使用它.只有当您的链接器尝试查找您的虚假函数的主体时,您才会收到错误消息.但是你的编译器会很酷.
有很多好处.你必须记住函数体并不总是在同一个源代码文件中.它可以在链接库中.此外,链接库可能具有特定的链接签名".使用条件定义您甚至可以在构建时使用范围原型选择正确的链接签名.尽管大多数人会使用函数指针
希望这会有所帮助.
I was reading the linked question which leads me to ask this question.
Consider the following code
int main()
{
string SomeString();
}
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?).
I figured out the following is valid.
int main()
{
string SomeFun();
SomeFun();
return 0;
}
string SomeFun()
{
std::cout << "WOW this is unexpected" << std::endl;
}
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?
Any thoughts?
解决方案Your prototype is just 'Forward Declaration'. Please check out the Wikipedia article.
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.
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.
Hope this helps.
相关文章