我的意思是:
int main() { void a() { // code } a(); }I mean something like:
int main() { void a() { // code } a(); return 0; }最满意答案
不,C ++不支持。
编辑:这个答案是老的。 同时,C ++ 11还可以实现类似的结果 - 看下面的答案。
也就是说,您可以拥有本地课程,并且可以具有(非static或static )功能,因此您可以在某种程度上得到这一点,尽管它有点像一个kludge:
int main() // it's int, dammit! { struct X { // struct's as good as class static void a() { } }; X::a(); return 0; }但是,我会质疑这个实践。 每个人都知道(嗯,现在你做,无论如何:) )C ++不支持本地功能,所以他们习惯于没有它们。 然而,它们不被用于该污泥。 我会在这段代码上花费一段时间来确保它只是在那里允许本地的功能。 不好。
Modern C++ - Yes with lambdas!
In current versions of c++ (C++11, C++14, and C++17), you can have functions inside functions in the form of a lambda:
int main() { // This declares a lambda, which can be called just like a function auto print_message = [](std::string message) { std::cout << message << "\n"; }; // Prints "Hello!" 10 times for(int i = 0; i < 10; i++) { print_message("Hello!"); } }Lambdas can also modify local variables through **capture-by-reference*. With capture-by-reference, the lambda has access to all local variables declared in the lambda's scope. It can modify and change them normally.
int main() { int i = 0; // Captures i by reference; increments it by one auto addOne = [&] () { i++; }; while(i < 10) { addOne(); //Add 1 to i std::cout << i << "\n"; } }C++98 and C++03 - Not directly, but yes with static functions inside local classes
C++ doesn't support that directly.
That said, you can have local classes, and they can have functions (non-static or static), so you can get this to some extend, albeit it's a bit of a kludge:
int main() // it's int, dammit! { struct X { // struct's as good as class static void a() { } }; X::a(); return 0; }However, I'd question the praxis. Everyone knows (well, now that you do, anyway :)) C++ doesn't support local functions, so they are used to not having them. They are not used, however, to that kludge. I would spend quite a while on this code to make sure it's really only there to allow local functions. Not good.
更多推荐
发布评论