【问题标题】:Constructor asking for a return type [duplicate]构造函数要求返回类型[重复]
【发布时间】:2013-11-12 19:14:13
【问题描述】:

首先,我对 Objective c 不太满意,我正在尝试将 C++ 类转换为 Objective C,但在我的类上实现时遇到了问题,这就是我为 c++ 得到的结果

p>
UniqueWord::UniqueWord(const string word, const int line)
{
wordCatalog=word;
count = 0;
addLine(line);
}

//Deconstructor.
UniqueWord::~UniqueWord(void)
{
} 

这就是我为 Objective C 得到的结果

@implementation UniqueWord

-(id)initWithString:(NSString*)str andline:(NSInteger)line{
    _wordCatalog=str;
    count=0;
    addline(line);
    return ?//return what? it states (Control reaches end of non-void function)
}

我对目标 c 中的课程真的很陌生,所以我还要求一个愚蠢的答案,“id”到底是什么,你如何使用它?

【问题讨论】:

  • 点击此链接了解 id 是什么:So question on id meaning
  • 请注意,C++ 中的构造函数确实有返回类型;根据语言标准,这是他们没有的名字。
  • 在声明 init 方法时,首选返回类型应该是 instancetype 而不是 id 以支持类型检查。

标签: c++ objective-c class object constructor


【解决方案1】:

Objective C 的构造函数有点不同。您应该创建如下内容:

-(instancetype)initWithString:(NSString*)str andline:(NSInteger)line{
    self = [super init];
    if(self == nil) return nil;
    _wordCatalog=str;
    count=0;
    addline(line);
    return self;
}

【讨论】:

    【解决方案2】:

    id 是 Objective-C 中的一个泛型类。这有点类似于 C++ 的void*,但执行环境提供了更多支持,因此不需要太多类型转换。

    C++ 中没有并行的概念:无类型的对象引用让您可以动态地使用对象,在运行时而不是在编译时检查调用的细节。

    还要注意,Objective-C 使用初始化器而不是构造器。两者的用途相似,但并不相同:构造函数可以与运算符new 一起运行,也可以与其分开运行,而初始化程序只能与进行分配的方法一起运行。此外,初始化器可以返回一个不同的对象来代替alloc 提供的对象;构造函数不能这样做。

    【讨论】:

      【解决方案3】:

      id 是指向 Objective-C 中任何对象的一个​​点。 init 方法返回一个已分配和实例化的对象。我会在https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/Initialization/Initialization.html@

      向您推荐有关初始化程序的 Apple 文档

      在使用上面文章所说的内容时,您会想写类似的东西。

      - (instancetype)initWithString:(NSString *)str andLine:(NSInteger)line {
          self = [super init];
          if (self) {
              _wordCatalog = str;
          }
          return self;
      

      【讨论】:

      • 编辑以展示该功能。
      【解决方案4】:

      init 方法的典型形式(您应该使用)如下所示:

      - (id)init
      {
          if ( (self = [super init] ) )
          {
              [other code you want in the constructor]
          }
      
          return self;
      }
      

      因此,对于您拥有的方法,它应该如下所示:

      -(id)initWithString:(NSString*)str andline:(NSInteger)line{
      
          if ( (self = [super init]) )
          {
              _wordCatalog=str;
              count=0;
              addline(line);
          }
      
          return self;
      }
      

      也就是说,除非超类有一个 initWithString:andline: 构造函数,在这种情况下你会使用

      if ( (self = [super initWithString:string andline:line) )
      

      作为 if 语句。

      【讨论】:

      • 在声明 init 方法时,首选返回类型应该是 instancetype 而不是 id 以支持类型检查。
      • @Zaph:对于名称以init开头的实例方法,编译器已经假定返回类型为instancetype
      • @newacct 是的,在这种情况下指定id 而不是instancetype 的价值/优势是什么?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-08
      • 1970-01-01
      • 1970-01-01
      • 2019-09-03
      相关资源
      最近更新 更多