【问题标题】:Does const go before or after CGFloat?const 是在 CGFloat 之前还是之后?
【发布时间】:2011-05-03 20:43:08
【问题描述】:

这还重要吗? Const before or const after? 我猜无论我将const 放在CGFloat 之前还是之后,它都会使CGFloat 的值保持不变,但是指针呢?这是否适用于 Objective-C:

// Example.h

extern CGFloat const kPasscodeInputBoxWidth;


// Example.m

CGFloat const kPasscodeInputBoxWidth = 61.0f;

【问题讨论】:

  • 什么指针呢?
  • 我的意思是,CGFloat的值的内存地址。这会保持不变吗?
  • kPasscodeInputBoxWidth 标识一个对象(非限定类型CGFloat)。该对象(与所有其他对象一样)"... exists, has a constant address, and retains its last-stored value throughout its lifetime ..."(参见C99 Standard 中的 6.2.4/2),因此,根据定义,该对象的地址是常量。

标签: objective-c c floating-point constants cgfloat


【解决方案1】:

它可以在之前或之后进行。在指针的情况下,重要的是const 是在星号之前还是之后结束:

const int *a;    // pointer to const int -- can't change what a points at
int const *a;    // same

int *const a;    // const pointer to int -- can't change the pointer itself.
                 // Note: must be initialized, since it can't be assigned.

【讨论】:

  • 你也可以拥有const int *const a;: 一个指向只读对象的只读指针:)
  • 问题与 CGFloat 不是整数指针有关。对于整数,Apple 指南声明“如果常量与其他常量无关,您可以使用 const 创建整数常量;否则,请使用枚举。”。他们只在使用 float 时提倡 const。见developer.apple.com/library/mac/documentation/Cocoa/Conceptual/…
  • @MaxMacLeod:确切的类型(int、long、float、double、CGFloat 等)在这里几乎无关紧要。
【解决方案2】:

没关系(我一直用前者,但我猜是风格问题):

const CGFloat kPasscodeInputBoxWidth = 61.0;
CGFloat const kPasscodeInputBoxWidth = 61.0;

至少在CGFloat 的当前版本中,它只是double 的typedef,所以就像使用常规原始数据类型一样。对于指针,const 的位置将决定它是指针还是常量值,所以这很重要。

【讨论】:

  • CGFloat 实际上是 float,而不是 double
  • 我认为它在 32 位和 64 位系统之间有所不同。我运行 64 位,对我来说是双倍的。
  • 有趣。我不知道。我刚刚通过CGBase.h:typedef CGFLOAT_TYPE CGFloat; 的第 89 行,我通过在 Xcode 中通过命令单击CGFloat 得到了它。但是,源代码对你来说怎么可能不同呢?不应该在所有机器上都一样吗?嗯...我以为我也在运行 64 位。你怎么知道不是@​​987654330@?
  • 我不确定,当你说它是浮点数时,我以为我在某个地方读到过,但对每个人来说可能都是双倍的。它不像 double 需要 64 位系统。即使我们有相同的源代码,通过预处理器定义,它们在理论上也可能不同。
猜你喜欢
  • 2011-07-27
  • 1970-01-01
  • 2014-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-30
  • 1970-01-01
相关资源
最近更新 更多