Objective C中的虚函数

spa*_*ana 15 objective-c

如何在Objective C中声明虚函数

virtual void A(int s);
Run Code Online (Sandbox Code Playgroud)

如何在Objective C中声明相同的内容.

-(void)A:(int)s //normal declaration
Run Code Online (Sandbox Code Playgroud)

Vla*_*mir 43

Objective-c不支持虚函数,或者说另一种方式 - obj-c类中的所有函数都是虚函数,因为方法调用是在运行时确定的.

如果您的子类重写超类中的方法,并使用指向超类的指针引用子类实例,则将调用子类方法:

@interface A{
}
-(void) someMethod;
@end

@interface B : A{
}
-(void) someMethod;
@end

...
A* obj = [[B alloc] init];
[obj someMethod]; // method implementation from B will be called
Run Code Online (Sandbox Code Playgroud)