gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:43:28 26 4
gpt4 key购买 nike

我在编译 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com