我正在研究霍兹纳的“视觉快速启动,目标-C”一书中的例子。我花了很多时间在每个例子上,让代码调试是更快的部分,然后逐步地告诉自己每一行代码的工作原理,每一行中的每个单词做什么,并决定为什么作者使用一种方法来做事情,而不是另一种。然后我用我自己的故事重复这个例子。这似乎是一个很好的方式,从一个结构化的程序员和一个类似oop的。它适用于这些例子,因为他一次只做一个概念。(我已经读过另外两本书了,这个想法对我没有用。一旦我被什么东西弄糊涂了,我就一直很困惑。在更长、更复杂的例子中有太多的变量)。
在当前的示例(第137页)中,Holzner使用了“静态”一词。我翻阅了这本书中的例子,决定了这个词的意思。我还阅读了的C++编程语言书中的描述(我理解C++和Objective并不完全相同)
(Bjarne Stroustup P 145)使用静态变量作为内存,而不是“可能被其他函数访问和损坏”的全局变量。
这就是我所理解的“静态”的意思。我认为这意味着静态变量的值永远不会改变。我认为这意味着它就像一个常量值,一旦你将它设置为1或5,它就不能在运行过程中被更改。
但是在这个示例代码中,静态变量的值确实会发生变化。所以我真的不清楚“静态”是什么意思。
(请忽略我留下的“跟进问题”。我不想在运行过程中更改任何内容,并冒着创建读取错误的风险。
谢谢你能给我的线索。我希望我没有把太多的细节放在这个问题上。
劳蕾尔
.
Program loaded.
run
[Switching to process 2769]
Running…
The class count is 1
The class count is 2
Debugger stopped.
Program exited with status value:0..
//
// main.m
// Using Constructors with Inheritance
//Quick Start Objective C page 137
//
#include <stdio.h>
#include <Foundation/Foundation.h>
@interface TheClass : NSObject
// FOLLOWUP QUESTION - IN last version of contructors we did ivars like this
//{
// int number;
//}
// Here no curly braces. I THINK because here we are using 'static' and/or maybe cuz keyword?
// or because in original we had methods and here we are just using inheirted methods
// And static is more long-lasting retention 'wise than the other method
// * * *
// Reminder on use of 'static' (Bjarne Stroustup p 145)
// use a static variable as a memory,
// instead of a global variable that 'might be accessed and corrupted by other functions'
static int count;
// remember that the + is a 'class method' that I can execute
// using just the class name, no object required (p 84. Quick Start, Holzner)
// So defining a class method 'getCount'
+(int) getCount;
@end
@implementation TheClass
-(TheClass*) init
{
self = [super init];
count++;
return self;
}
+(int) getCount
{
return count;
}
@end
// but since 'count' is static, how can it change it's value? It doeeessss....
int main (void) {
TheClass *tc1 = [TheClass new] ;
printf("The class count is %i\n", [TheClass getCount]);
TheClass *tc2 = [TheClass new] ;
printf("The class count is %i\n", [TheClass getCount]);
return 0;
}发布于 2010-11-02 01:55:38
为了进一步阐明--特别是的答案--在对象的所有实例中,在方法调用之间,静态变量将保持不变。
例如,声明以下方法:
- (int)getNumber {
static int number = 0;
return ++number;
}将在任何给定时间跨给定类的所有实例返回1、2、3、4等。很好,嗯?
发布于 2010-11-02 01:39:42
“静态”与C++ "const“不是一回事。相反,它是一种语句,即变量只声明一次,并且将保持(因此是静态的)内存中。假设你有一个功能:
int getIndex()
{
static int index = 0;
++index;
return index;
}在这种情况下,“静态”命令编译器将索引值保留在内存中。每次访问它时,它都会改变: 1,2,3,.。
将此与以下情况进行比较:
int getIndex()
{
int index = 0;
++index;
return index;
}这将每次返回与每次创建索引变量相同的值: 1,1,1,1,1,……。
https://stackoverflow.com/questions/4074334
复制相似问题