“虚拟"Objective-c 中方法的返回类型 [英] "virtual" method's return type in objective-c

查看:28
本文介绍了“虚拟"Objective-c 中方法的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应该是抽象的类.在其中一个抽象方法中,返回类型可能是 class1、class2 或 class3 的实例,具体取决于实现该方法的类.我想知道我应该如何在抽象类中声明该方法.我考虑过使用动态类型,但我希望将返回类型限制为 3 个类之一,而不是每种类型,此外我不确定我是否可以覆盖它,以便在继承类中返回类型不会匹配抽象类中的返回类型.

I have a class which is supposed to be abstract. In one of it's abstract methods the return type may be an instance of class1,class2 or class3, depending on the class that's implementing the method. I'm wondering how should I declare the method in the abstract class. I thought about using dynamic typing, but I want the return type to be restricted to one of the 3 classes, not every type, and in addition I'm not sure I can override it so that in the inheriting class the return type will not match the return type in the abstract class.

如果你能帮助我,我会很高兴,
Tnx!

I'd be glad if you could help me with this,
Tnx!

推荐答案

看看这个:

#import <Foundation/Foundation.h>

@interface A : NSObject { }
- (A*) newItem;
- (void) hello;
@end

@interface B : A { int filler; }
- (B*) newItem;
- (void) hello;
- (void) foo;
@end

@implementation A
- (A*) newItem { NSLog(@"A newItem"); return self; }
- (void) hello { NSLog(@"hello from A"); }
@end

@implementation B
- (B*) newItem { NSLog(@"B newItem"); return self; }
- (void) hello { NSLog(@"hello from B: %d", filler); }
- (void) foo { NSLog(@"foo!"); }
@end

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    A *origA = [A new];
    A *myA = [origA newItem];

    NSLog(@"myA: %@", myA);

    B *origB = [B new];
    B *myB = [origB newItem];
    A *myBA = [origB newItem];

    NSLog(@"myB: %@
myBA: %@", myB, myBA);

    [origA hello];
    [origB hello];
    [myA hello];
    [myB hello];
    [myBA hello];

    NSLog(@"Covariance?");

    [pool drain];
    return 0;
}

这是相当简洁的语法,内存管理很糟糕,但是您可以看到 newItem 是虚拟的(将 newItem 发送到 myBA 返回一个B) 和协变,这似乎是你想要的.

This is rather condensed syntax, and memory management sucks, but you can see that newItem is virtual (sending newItem to myBA returns a B) and covariant, which seems to be what you want.

请注意,您也可以这样做:

Note that you could also do:

    B *myAB = (B*)[origA newItem];

但是返回一个 A,并且发送 foo 给它会告诉你这个类没有响应选择器 #foo.如果你省略了 (B*) 强制转换,你会在编译时收到一个警告.

but that returns an A, and sending foo to it would tell you that the class does not respond to selector #foo. If you omitted the (B*) cast, you would get a warning about this at compile time.

但是ISTM认为协方差在Objective-C中不是大问题.

But ISTM that covariance is no big problem, in Objective-C.

这篇关于“虚拟"Objective-c 中方法的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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