如何访问父类中声明的方法?
我想知道是否可以访问在父类中声明的方法,该方法已被覆盖(如果我犯了任何错误,请原谅我的英语)。代码片段:
#import <stdio.h>
#import <objc/Object.h>
@interface Parent : Object
-(void) message;
@end
@implementation Parent
-(void) message
{
printf("\nParent\n");
}
@end
@interface Child : Parent
//-(void) message;
@end
@implementation Child
-(void) message
{
printf("\nChild\n");
}
@end
int main(int argc, const char* argv[])
{
Parent* p = [[Child alloc] init];
[p message];
[p free];
return 0;
}
所以我的问题是,当 Parent* 指针指向 Child 对象时,如何调用父类中定义的“message”方法。 Objective-C(作为纯动态语言)自动调用Child的方法,但是是否可以通过*p指针从外部调用父类的方法?我的意思是,当我向“p”发送消息“message”时,屏幕上将显示“Parent”而不是“Child”。
谢谢。
I wonder whether it's possible to access a method declared in a parent class, which has been overrided (Sorry for my English if I make any mistakes). The code snippet:
#import <stdio.h>
#import <objc/Object.h>
@interface Parent : Object
-(void) message;
@end
@implementation Parent
-(void) message
{
printf("\nParent\n");
}
@end
@interface Child : Parent
//-(void) message;
@end
@implementation Child
-(void) message
{
printf("\nChild\n");
}
@end
int main(int argc, const char* argv[])
{
Parent* p = [[Child alloc] init];
[p message];
[p free];
return 0;
}
So my question is, how can I call the 'message' method defined in the parent class, when the Parent* pointer points to a Child object. Objective-C (being a pure dynamic language) automatically calls the Child's method, but is it possible to call the method of the parent class from outside, through the *p pointer? I mean, when I send the message 'message' to 'p', not "Child" but "Parent" would be shown on the screen.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将子
messgae
方法修改为,Modify the child
messgae
method as,经过几天的学习 Objective-C 我找到了解决方案。该解决方案通过函数指针显式调用该方法,而不是发送消息。我知道这不是一个好的做法,但我认为在某些情况下这是有必要应用的。所以代码:
After days of learning objective-c I've found the solution. This solution explicitly calls the method through function pointer, instead of sending a message. I know this is not a good practice, however I think there are situations when this is necessary to apply. So the code: