objective-c - objective-C 和 objective-C++ 中静态成员的定义

标签 objective-c static compilation objective-c++ redefinition

我在编译 objective-c 源代码和 objective-c++ 源代码时有区别。

这里是 class1 和 Class2 在 test.h 中的声明:

#import <Foundation/Foundation.h>

@interface Class1 {
}
@end

@interface Class2 {
}
@end

现在,这是 test.m 中的 Objective-C 实现:

#import "test.h"

@implementation Class1
/* static member */
static int mystatic;
@end


@implementation Class2
/* static member */
static int mystatic;
@end

我用这个命令编译成功:

gcc -arch armv6 -isysroot /Developer/.../iPhoneOS5.0.sdk -x objective-c -c test.m

现在我完全使用这个 Objective-C++ 实现 test.mm(完全相同的来源):

#import "test.h"

@implementation Class1
/* static member */
static int mystatic;
@end


@implementation Class2
/* static member */
static int mystatic;
@end

并使用此命令行编译(-x 选项的区别):

gcc -arch armv6 -isysroot /Developer/.../iPhoneOS5.0.sdk -x objective-c++ -c test.mm

但是我得到一个错误:

test.mm:11 error: redefinition if 'int mystatic'

为什么我在 ObjC++ 而不是 ObjC 中得到这个错误?

最佳答案

这归结为 C 和 C++ 之间的区别。在 C 中,可以重新定义同名同类型的静态变量;在 C++ 中,这样做是错误的。

来自 C 标准:

A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with a storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definitions for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.

来自 C++ 标准:

C.1.2, 3.1 Change: C++ does not have “tentative definitions” as in C. E.g., at file scope,

int i ;
int i ;

is valid in C, [but it is] invalid in C++.

就 Objective C 而言,该语言不支持在类级别作用域的变量;在 @implementation block 内声明 static int mystatic; 与在 @implementation block 外声明它具有完全相同的效果。要模拟类范围的变量,请在类方法中使用函数范围的静态变量。

关于objective-c - objective-C 和 objective-C++ 中静态成员的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11346035/

相关文章:

c++ - 在 C++ 中查找静态初始化器和析构器

java - 将使用 1.6.0.24 编译的 War 部署到 1.6.0.22 时出现问题

compilation - 编译 Inno Setup 脚本时是否可以调用批处理文件?

iphone - 使用 UIScrollView 生成问题

c++ - 将 C++ 类的实例转换为 NSObject,然后添加到 NSMutableArray

c# - 静态类中没有静态嵌套类 C#

windows - 静态库与动态库性能

c++ - 编译成可执行文件

iphone - 自定义 UITableViewCell 问题

ios - 由于未捕获的异常 '_HKObjectValidationFailureException' 而终止应用程序