为什么在Objective C构造函数中使用[super init]? [英] Why to use [super init] in Objective C constructors?

查看:177
本文介绍了为什么在Objective C构造函数中使用[super init]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个名为Item的类。它是NewsItem和TwitterItem的超类。

Say I have a class named Item. Which is a superclass of NewsItem and TwitterItem.

如果我想创建一些NewsItem的,我必须使用(在构造函数中)

If I want to create some NewsItem's do I have to use (inside constructor)

    self = [super init];

如果是,为什么?在Java / C#中,我只会这么做,

If yes, why? In Java/C# I would just do,

    NewsItem n = new NewsItem();



我不需要对Java / C#中的超类做任何事情。

I don't have to do anything with superclasses in Java/C#. Just can't grasp it.

推荐答案

在Java和C#中,编译器会自动使你的构造函数调用超类构造函数不明确地调用它。例如,Java教程说明了这一点:

In Java and C#, the compiler automatically makes your constructor call the superclass constructor if you don't explicitly call it. For example, the "Java Tutorials" say this:


如果构造函数没有显式调用超类构造函数,Java编译器会自动插入对超类的无参构造函数的调用。如果超类没有无参构造函数,你将得到一个编译时错误。 Object有这样的构造函数,所以如果Object是唯一的超类,就没有问题。

If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

在Objective-C中,不会自动做,所以你必须自己做。

In Objective-C, the compiler doesn't do it automatically, so you have to do it yourself.

这篇关于为什么在Objective C构造函数中使用[super init]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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