HOWTO访问父类中声明的方法? [英] HOWTO access the method declared in the parent class?

查看:143
本文介绍了HOWTO访问父类中声明的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以访问在父类中声明的方法,该方法已被覆盖(如果我犯了任何错误,对不起我的英语)。代码段:

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;
}

所以我的问题是,如何调用在此定义的'message'方法父类指针指向Child对象时的父类。 Objective-C(纯动态语言)自动调用Child的方法,但是可以通过* p指针从外部调用父类的方法吗?我的意思是,当我将消息'消息'发送到'p'时,不是Child,而是Parent将显示在屏幕上。

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.

谢谢。

推荐答案

经过几天的学习后,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:

#import <stdio.h>
#import <stdlib.h>
#import <Foundation/Foundation.h>

@interface Parent : NSObject     // I switched from Object to NSObject
-(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[])
{
    IMP f;
    Parent* p = [[Child alloc] init];  //p could be (Child*) too
    f = [[p superclass] instanceMethodForSelector: @selector(message)];
    f(p, @selector(message));

    [p release];
    return EXIT_SUCCESS;
}

这篇关于HOWTO访问父类中声明的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆