Objective-C 错误:初始化元素不是常量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/459530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objective-C error: initializer element is not constant
提问by Przemyslaw Zych
Why does the compiler give me the following error message on the provided code: "initializer element is not constant". The corresponding C/C++ code compiles perfectly under gcc.
为什么编译器在提供的代码上给我以下错误消息:“初始化元素不是常量”。对应的C/C++代码在gcc下完美编译。
#import <Foundation/Foundation.h>
const float a = 1;
const float b = a + a; // <- error here
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// insert code here...
NSLog(@"Hello, World!");
[pool drain];
return 0;
}
回答by dreamlax
That code will only compile correctly if the const floatstatements appear somewhere other than the file scope.
只有当const float语句出现在文件范围之外的其他地方时,该代码才会正确编译。
It is part of the standard, apparently. It is important that all file-scope declared variables are initialised with constant expressions, not expressions involving constant variables.
显然,它是标准的一部分。重要的是所有文件范围声明的变量都使用常量表达式初始化,而不是包含常量变量的表达式。
You are initialising the float 'b' with the value of another object. The value of any object, even if it is a const qualified, is not a constant expression in C.
您正在使用另一个对象的值初始化浮点 'b'。任何对象的值,即使它是 const 限定的,也不是 C 中的常量表达式。
回答by Quinn Taylor
@dreamlaxis correct, you can't have a const declaration whose initialization depends upon another (const) variable. If you need one to depend on the other, I suggest creating a variable that you can treat as a constant and initialize it only once. See these SO questions for details:
@dreamlax是正确的,你不能有一个 const 声明,其初始化依赖于另一个(const)变量。如果您需要一个依赖另一个,我建议创建一个变量,您可以将其视为常量并仅将其初始化一次。有关详细信息,请参阅这些 SO 问题:
回答by hhafez
I don't have Xcode on my machine here so I can't try my example,
我的机器上没有 Xcode,所以我无法尝试我的示例,
But can you try
但是你能不能试试
#define A (1)
#define B (A + A)
const float a = A;
const float b = B;

