evrytime,when I define the a function in the main() ,the compile will note: a function definition is not allowed here before "{" token. but,define the function in the public scode is all ok.
U cannot declare a function within a function and main() is just another function.
Imagine going to a library to get a book. U tell the librarian what book u want and instead of knowing where the book u want is, she instead asks u to get a reference card from a different book and to bring that reference card back to her. At which point she tells u where that original book u wanted is...why doesn't she just have that reference card with her to save u all that trouble of finding it among all those books?
thank you ,the first sentance can save my problems,but I think the following example is more usefull. unfortunatly, I am a chinese,english is not very good. could you please explain the example for me more ease to understand.
There is no technical problem in allowing closures as far as objects with static storage duration are involved. Objects with an automatic storage duration gives rise to the '"functional argument problem".
The C programming language historically avoids the main difficulty of the funarg problem by not allowing function definitions to be nested
The alternative is for the language to accept that certain use cases will lead to undefined behaviour, as in the proposal for lambda expressions in C++.
#include <iostream>
#include <memory>
#include <functional>
struct base { virtualvoid foo( int v ) const = 0 ; virtual ~base() {} } ;
std::shared_ptr<base> pb ;
std::function< void(int) > function()
{
staticint s = 10 ;
int a = 10 ;
// ok, s has a static storage duration;
// object of type 'A' can be safely used after 'function' returns
struct A : base { virtualvoid foo( int v ) const /*override*/ { s += v ; } } ;
pb = std::make_shared<A>() ;
pb->foo(25) ;
std::cout << s << '\n' ; // 35
// C++11: closure; variables in the outer lexical scope are captured by reference
// will result in undefined behaviour if 'bar' is used outside 'function'
auto bar = [&] ( int v ) { s += v ; a += v ; } ;
bar(33) ;
std::cout << s << ' ' << a << '\n' ; // 68 43
// C++11: a is captured by value
// 'baz' is well behaved even if it is used after 'function' returns
auto baz = [&s,a] ( int v ) { s += v + a ; } ;
return baz ;
}