有人能简单解释OOP环境中的方法与函数吗?


当前回答

在C++中,有时使用方法来反映类的成员函数的概念。然而,最近我在《C++编程语言第四版》一书中发现了一个声明,第586页“派生类”

虚函数有时称为方法。

这有点令人困惑,但他说,有时,C++创建者倾向于将方法视为可以在对象上调用的函数,并且可以表现为多态。

其他回答

在OO世界中,这两个词通常用来表示同一件事。

从纯数学和CS的角度来看,当使用相同的参数(f(x,y)=(x+y))调用函数时,函数将始终返回相同的结果。另一方面,方法通常与类的实例相关联。尽管如此,大多数现代OO语言在很大程度上不再使用术语“函数”。许多静态方法可以很像函数,因为它们通常没有状态(不总是真的)。

类上的方法作用于类的实例,称为对象。

class Example
{
   public int data = 0; // Each instance of Example holds its internal data. This is a "field", or "member variable".

   public void UpdateData() // .. and manipulates it (This is a method by the way)
   {
      data = data + 1;
   }

   public void PrintData() // This is also a method
   {
      Console.WriteLine(data);
   }
}

class Program
{
   public static void Main()
   {
       Example exampleObject1 = new Example();
       Example exampleObject2 = new Example();

       exampleObject1.UpdateData();
       exampleObject1.UpdateData();

       exampleObject2.UpdateData();

       exampleObject1.PrintData(); // Prints "2"
       exampleObject2.PrintData(); // Prints "1"
   }
}

函数和方法看起来非常相似。它们也有输入和返回输出。区别在于方法在类内部,而函数在类外部。

函数是执行特定任务的一组指令或过程。它可以用来将代码分割成易于理解的部分,这些部分也可以被调用或重用。

方法是可以对对象执行的操作。它也称为存储为对象财产的函数。

主要区别:函数不需要任何对象并且是独立的,而方法是一个函数,它与任何对象链接。

//firstName() is the function

function firstName(){
 cosole.log('John');
}

firstName() //Invoked without any object

const person = {
  firstName: "John",
  lastName: "Doe",
  id: 5566,
};

//person.name is the method
person.name = function() {
  return this.firstName + " " + this.lastName;
};

document.getElementById("demo").innerHTML =
"My father is " + person.name() //performs action on object; 

函数是主要属于面向过程编程的概念,其中函数是一个可以处理数据并返回值的实体

方法是面向对象编程的概念,其中方法是类的成员,该类主要对类成员进行处理。