在基类中使用派生类

时间:2013-02-13 21:44:13

标签: objective-c oop inheritance

是否可以在Objective-C中使用基类中的继承类,例如:

Class BaseClass
{
  InheritedClass memberVariable;
}

Class InheritedClass : BaseClass
{
  // implementation goes here
}

编辑:更详细的解释:

想象一下现实世界的情况,你有

Album:
- Title
- Artist

Song:
- Title
- Artist
- Duration

所以你可以说Album类可以是Song类的基类,如下所示:

Class Album
{
  Title;
  Artist;
}

Class Song : Album
{
  Duration;
}

现在,如果您需要在专辑类中存储专辑的歌曲,您最终会得到以下内容:

Class Album
{
  Title;
  Artist;
  Songs[];
}

或者我一般都错了,或者遗漏了一些基础知识?

2 个答案:

答案 0 :(得分:1)

这是可能的,但您可能无法存储C ++中可能存在的对象,您需要存储指向它的指针:

Class BaseClass
{
    InheritedClass* memberVariable;
}

然后指针可能指向一个Inherited Class对象。

答案 1 :(得分:1)

是的,一个类有一个实例变量(你正在调用成员变量的ObjC术语)或属性,它的类型是它自己的子类是完全可以接受的。

这是一个简单的,可编译的程序,它演示了你在Objective-C中提出的问题:

#import <Foundation/Foundation.h>

@class Song;

@interface Album : NSObject
    @property (strong) NSString *artist;
    @property (strong) NSString *title;
    @property (strong) NSArray *songs; 
    @property (strong) Song *bestSong;
@end

@interface Song : Album
    @property (weak) Album *album;
    @property NSTimeInterval duration;
@end

@implementation Album
@end

@implementation Song
@end

int main(int argc, char *argv[]) {
    @autoreleasepool {
        Album *album = [[Album alloc] init];
        Song *song1 = [[Song alloc] init];
        Song *song2 = [[Song alloc] init];
        album.songs = @[song1, song2];
        album.bestSong = song1;
        song1.album = album;
        song2.album = album;

        NSLog(@"Album: %@", album);
        NSLog(@"songs: %@", album.songs);
        NSLog(@"bestSong: %@", album.bestSong);
    }
}

输出:

Album: <Album: 0x7fcc3a40a3e0>
songs: (
    "<Song: 0x7fcc3a40a5e0>",
    "<Song: 0x7fcc3a40a670>"
)
bestSong: <Song: 0x7fcc3a40a5e0> bestSong: <Song: 0x7ff48840a580>