开发者

object oriented programming

开发者 https://www.devze.com 2022-12-25 04:46 出处:网络
Is the nesting of functions possible in t开发者_JS百科he object oriented languages like C#, Java, C++ etc . If so, can anyone give an example?Having nested function is irrelevant to being object-orien

Is the nesting of functions possible in t开发者_JS百科he object oriented languages like C#, Java, C++ etc . If so, can anyone give an example?


Having nested function is irrelevant to being object-oriented.


  • C# doesn't have nested functions, but you can use lambdas (See Why doesn't C# have lexically nested functions?). So are all other programming languages that support anonymous functions (including C++0x).
  • You may create a local class, and overload the call operator to simulate a nested function (See is it possible in C or C++ to create a function inside another?).
  • Meanwhile, many non-object-oriented languages like (the original) Pascal support nested functions natively, and GCC support it in C as an extension.


Implementing Nested Functions in C#.


As other answers have pointed out, because you can create anonymous functions in most languages these days, you can assign such a function object to a variable, and that effectively results in a local function (although recursion may be tricky).

In C++ prior to C++1x anonymous functions (known as lambdas) are not yet available. However, you can still declare a function inside a function, because you can declare a class or struct inside a function. If you make that class implement operator(), then instantiate the class and store it in a named variable, you will have effectively achieved the same as a lamda in C++1x.

The problem is that it will (a) be much more verbose and (b) it won't be permissible as an argument to a template.


Java is another one OO language. It does not support nested methods, but it does support nested class (it could help in workaround): http://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html

0

精彩评论

暂无评论...
验证码 换一张
取 消