本文介绍了将基类指针指向目标c中的派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为ModelBase的基类,还有一个名为"Person"的派生类.现在,在person的init方法中,我有类似的东西

I have a base class called ModelBase and I have a derived class called "Person".Now in the init method of person, I have something like

-(Person*) init {
     if(self = [super init])
         return self;

     return nil;
}

但是,目标C抱怨说初始化"struct ModelBase *",预期"struct Person *"的不兼容的Objective-C类型.我只用[super init]初始化self,这是初始化指向派生类的基类指针.

However, Objective C complains thatIncompatible Objective-C types initializing 'struct ModelBase *', expected 'struct Person *'. I'm only initializing self with [super init] which is initializing a base class pointer to a derived class.

我想念什么?

推荐答案

您是否声明了要返回的ModelBase初始化方法(ModelBase *)?如果是这样,请将其更改为返回(id).您会注意到,可可中的大多数初始化器都是出于这个原因而返回(id).

Did you declare your ModelBase init method to return (ModelBase*) ? If so, change it to return (id) instead. You'll notice that most initializers in Cocoa return (id) for this very reason.

代替

- (ModelBase*)init;

您想要的

- (id)init;

这篇关于将基类指针指向目标c中的派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-09 11:09