You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In some programming languages, function overloading or method overloading is the ability to create multiple functions of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.
Method overriding, in object-oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. The implementation in the subclass overrides (replaces) the implementation in the superclass by providing a method that has same name, same parameters or signature, and same return type as the method in the parent class. The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed. Some languages allow a programmer to prevent a method from being overridden.
重载
如维基百科所讲,简言之,重载(Overload)指在同一个类中,存在相同函数名但不同参数个数或不同参数类型或不同返回值的函数。但由于 Obj-C 是消息结构的语言,其意义上的方法调用实质上是消息传递。
我们定义一个继承自
NSObject
的Computer
类,其拥有两个实例方法。尝试将上述代码翻译为 C++,xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc main.m -o main-64.cpp
。由于 Obj-C 是消息结构的语言,objc_msgSend
处便是其消息传递之处,我们可以发现原本的方法都被变成了字符串:sel_registerName("alloc")
、sel_registerName("init")
、sel_registerName("run")
和sel_registerName("run:")
。实际上这些字符串就是 Obj-C 方法的方法名,方法名忽略了参数名以及返回值,实例方法与类方法的区别也只是不同的消息接收对象。所以严格意义上讲,Obj-C 是不支持方法重载的,因为它不允许同名函数的存在。但如果按不同参数个数也属于方法重载来说,Obj-C 仅支持参数个数不同的重载,每个参数都将在方法名后多生成一个:
从而可以区分。重写
完全不同于重载,重写(Override)是指在子类中重写父类的方法,且方法名、参数类型、参数个数、返回值类型等必须一致。Obj-C 是完全支持方法重写的:
Reference
The text was updated successfully, but these errors were encountered: