Difference between a method and a function

有人可以在OOP上下文中提供方法函数的简单解释吗?


A function is a piece of code that is called by name. It can be passed data to operate on (ie the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.

A method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:

  • A method is implicitly passed the object on which it was called.
  • A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).
  • (this is a simplified explanation, ignoring issues of scope etc.)


    A method is on an object.
    A function is independent of an object.

    For Java, there are only methods.
    For C, there are only functions.

    For C++ it would depend on whether or not you're in a class.


    'method' is the object-oriented word for 'function' . That's pretty much all there is to it (ie., no real difference).

    Unfortunately, I think a lot of the answers here are perpetuating or advancing the idea that there's some complex, meaningful difference.

    Really - there isn't all that much to it, just different words for the same thing.

    [late addition]


    In fact, as Brian Neal pointed out in a comment to this question, the C++ standard never uses the term 'method' when refering to member functions. Some people may take that as an indication that C++ isn't really an object-oriented language; however, I prefer to take it as an indication that a pretty smart group of people didn't think there was a particularly strong reason to use a different term.

    链接地址: http://www.djcxy.com/p/350.html

    上一篇: var关键字的用途是什么,什么时候应该使用它(或省略它)?

    下一篇: 方法和函数之间的区别