Objective-C中此数据结构(C++)的替代方案

Alternative for this data structure(C++) in Objective-C

本文关键字:方案 C++ 数据结构 Objective-C      更新时间:2023-10-16

我在C++中有这个数据结构(结构):

struct Vector3f
{
    float x;
    float y;
    float z;
    Vector3f()
    {
    }
    Vector3f(float _x, float _y, float _z)
    {
        x = _x;
        y = _y;
        z = _z;
    }
};

我最近一直在学习和使用Objective-C。 我发现有很多事情我在 Objective-C 中做不到,而我在C++中却能做到。 所以,我希望能够在Objective-C中使用构造函数来做到这一点。 我知道Objective-C不支持像C++那样的函数重载。 因此,不需要第一个构造函数。

您只需使用三个属性:

@interface Vector : NSObject
@property(nonatomic, assign) float x, y, z;
- (id)init;
- (id)initWithX:(float)x y:(float)y z:(float)z;
@end
@implementation Vector
- (id)init {
    // Members default to 0 implicitly.
    return [super init];
}
- (id)initWithX:(float)x y:(float)y z:(float)z {
    if (self = [super init]) {
        self.x = x;
        self.y = y;
        self.z = z;
    }
    return self;
}
@end

请注意,此处重写init是可选的,因为它所做的只是调用超类的init方法。

相关文章: