应将各种变量和方法类型放在标题中的位置 [英] Where various variable and method types should be placed in a header

查看:35
本文介绍了应将各种变量和方法类型放在标题中的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,如果我在头文件中的某些位置放置某些声明,则会出现编译错误.我已经在代码中添加了关于我认为某些事情发生的地方的评论;他们说得对吗?

I've noticed that I get compilation errors if I place certain declarations in certain places in my header file. I've put comments into the code as to where I think certain things go; are they correct?

@interface Level : CCNode { 
    //Instance variables?
    PlayBackgroundLayer* playBGLayer;
    PlayUILayer* playUILayer;
    PlayElementLayer* playElementLayer;
}

//Static methods?
+(void) InitLevel: (int) levelNumber;
+(Level*) GetCurrentLevel;

//Property declarations for instance variables?
@property (nonatomic, retain) PlayBackgroundLayer* playBGLayer;
@end

//Static variables?
Level* currentLevel;
PlayTilemapLayer* playTilemapLayer;

推荐答案

你在所有方面都是正确的,除了一个.您的最后一个变量不是静态变量,它们是全局变量.静态变量只是用 static 关键字声明的变量,它们的含义与其他语言略有不同.它们不是类变量,它们是仅对声明它们的文件可见的变量,并且仅在声明它的范围内可见(如果您在函数中声明它,其他函数将看不到它).但是,如您所料,无论您拥有多少个实例,它们都只会被声明一次.如果你像你一样在没有 static 关键字的情况下在接口之外声明一些东西,其他类将导入它们.但是,这不是实现这一目标的理想方式(如果有多个类导入此标头,您可能会遇到重新定义错误).

You are correct on all counts except one. Your last variables are not static variables, they are global variables. Static variables are simply variables that are declared with the static keyword and they mean something a little different than other languages. They aren't class variables, they are variables that are visible only to the file that they are declared in, and only then in the scope that it was declared (if you declare it inside a function other functions won't see it). However, as you would expect, they are only declared once regardless of how many instances you have. If you declare something outside an interface without the static keyword as you did, other classes will import them. However, this is not the ideal way to accomplish this (you might get redefinition errors if more than one class imports this header).

另外,一个警告是,属性不需要有一个显式的后备变量(如果你使用 @synthesize 关键字,编译器会为你创建一个),但当然如果你渴望一个没有错.

Also, one caveat, is that properties don't need to have an explicit backing variable (the compiler will create one for you if you use the @synthesize keyword), but of course if you desire one there is nothing wrong with it.

最后,您应该注意静态方法 类方法不是实例方法的唯一原因是因为它们以 加号 (+) 字符开头,而不是以 减号 (-) 字符开头.

Finally, you should note that the only reason that your static methods class methods are not instance methods is because they start with a plus (+) character as opposed to a minus (-) character.

这篇关于应将各种变量和方法类型放在标题中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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