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

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

问题描述

我注意到,如果我在头文件中的某些地方放置某些声明,我会收到编译错误。我把代码中的意见,我认为某些事情去;是否正确?

  @interface级别:CCNode {
//实例变量?
PlayBackgroundLayer * playBGLayer;
PlayUILayer * playUILayer;
PlayElementLayer * playElementLayer;
}

//静态方法?
+(void)InitLevel:(int)levelNumber;
+(Level *)GetCurrentLevel;

//实例变量的属性声明?
@property(nonatomic,retain)PlayBackgroundLayer * playBGLayer;
@end

//静态变量?
Level * currentLevel;
PlayTilemapLayer * playTilemapLayer;


解决方案

你最后的变量不是静态变量,它们是全局变量。静态变量只是用static关键字声明的变量,它们意味着与其他语言稍有不同。它们不是类变量,它们是只对它们声明的文件可见的变量,只有在它被声明的范围内才可见(如果你在一个函数中声明它,其他函数不会看到它)。但是,正如你所期望的,它们只被声明一次,而不管你有多少个实例。如果你在没有static关键字的接口之外声明一些东西,那么其他类就会导入它们。但是,这不是完成此操作的理想方式(如果多个类导入此标题,则可能会导致重定义错误)。



另外,需要注意的一点是,属性不需要显式的支持变量(如果使用 @synthesize 关键字),但当然如果你想要一个没有错误。



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

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;

解决方案

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).

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天全站免登陆