1

是否有可能,特别是在 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;
}

现在,如果你需要在 Album 类中存储专辑的歌曲,你最终会得到这样的结果:

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

还是我通常错了,或者缺少一些基础知识?

4

2 回答 2

1

这是可能的,但您可能不会像在 C++ 中那样存储对象,您需要存储指向它的指针:

Class BaseClass
{
    InheritedClass* memberVariable;
}

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

于 2013-02-13T21:47:40.040 回答
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>
于 2013-02-13T23:38:11.207 回答