Objective-C不和C++那样有函数重载

今天有学员问在看Programming iOS 6的书上看到OC里不能像C++那样形式做函数重载的问题.

No Overloading

The data type returned by a method, together with the data types of each of its param‐ eters in order, constitute that method’s signature. It is illegal for two methods of the same type (class method or instance method) to exist in the same class with the same name but different signatures.

So, for example, you could not have two MyClass instance methods called myMethod, one of which returns void and one of which returns an NSString. Similarly, you could not have two MyClass instance methods called myMethod:, both returning void, one taking a CGFloat parameter and one taking an NSString parameter. An attempt to vi‐ olate this rule will be stopped dead in its tracks by the compiler, which will announce a “duplicate declaration” error. The reason for this rule is that if two such conflicting methods were allowed to exist, there would be no way to determine from a method call to one of them which method was being called.

You might think that the issue could be decided by looking at the types involved in the call. If one myMethod: takes a CGFloat parameter and the other myMethod: takes an NSString parameter, you might think that when myMethod: is called, Objective-C could look at the actual argument and realize that the former method is meant if the argument is a CGFloat and the latter if the argument is an NSString. But Objective-C doesn’t work that way. There are languages that permit this feature, called overloading, but Objective- C is not one of them. 

我在这阐述一下这2个OO语言之间的一些异同:

1, 两者最大的相同便是: 都是从 C 演化而来的面向对象语言, 两者都兼容标准 C 语言.

2, 两者最大的不同便是: Objective C 是完全动态(运行时绑定)的,而 C++是部分动态的(编译时绑定和运行时绑定)。

Objective C 支持在运行时动态类型决议(dynamic typing),动态绑定(dynamic binding)以及动态装载(dynamic loading);
C++ 是编译时静态绑定,通过嵌入类(多重继承)和虚函数(虚表)来模拟实现。
Objective C 在语言层次上支持动态消息转发,其消息发送语法为 [object function]; 而且C++ 为 object->function()。 两者的语义也不同,在 Objective C 里是说发送消息到一个对象上,至于这个对象能不能响应消息以及是响应还是转发消息都不会 crash; 而在 C++ 里是说对象进行了某个操作,如果对象没有这个操作的话,要么编译会报错(静态绑定),要么程序会 crash 掉的(动态绑定)。

3, Objective C 不支持多重继承, 而 C++ 支持。 不过 Objective C 通过 proxy(代理) 或 Category(类别) 可以更优雅地实现这一特性。这一点也包括了 overriding(覆盖) 和 overloading(重载) 两者的不同。Objective C 不支持函数重载。

4, 函数名字解析根据也不同,Objective C 的函数名字解析是根据函数名称 + 标签名称的, 而 C++ 只根据函数名称。 因此在 Objective C 中以下是合法的,因为两者解析出来函数符号分别类似于 foo:bar1: 和 foo:bar2: 是不同的:

-(int)foo:(int) bar bar1:(int)bar;

-(char*)foo:(int) bar bar2:(int)bar;

而在 C++ 中以下是非法的, 编译将出错, 因为两者解析出来函数符号都是类似于 foo:int, 编译器无法辨别:

int foo(int bar, int bar1);

char* foo(int bar, int bar2);

5, Objective-C 没有 C++ 里有的构造函数和析构函数, 其对应为 alloc-init/dealloc;

6, Objective-C 2.0 了加入了垃圾回收机制(在 iPhone 和 iPad  等iOS系统上不可用), 而 C++ 没有;

7, Objective-C 不允许在 Stack 上分配内存,只能在 Heap 上分配,而 C++ 两者都可以;

8, Objective-C 不支持模板,而 C++ 支持;Objective-C 不支持命名空间,而 C++ 支持;

9,Objective-C 也不支持函数缺省默认参数,而 C++ 支持;

10, Objective-C 是 Smalltalk 系的, 而 C++ 是 Simula 系的。

 

文章分类 iPhone应用开发

发表评论