gpt4 book ai didi

objective-c - 我应该如何在 ObjC 中为 C 数组编写属性声明?

转载 作者:行者123 更新时间:2023-12-02 08:37:18 26 4
gpt4 key购买 nike

我目前有这段代码:

@interface Matrix4 : NSObject
{
float mat[16];
}
@property (readonly) float mat[1];

我希望属性要么给我 mat 数组,要么有多个属性让我只读访问 mat[1]、mat[2] 等。

我目前有“属性不能有函数类型 float[1] 的数组”作为错误消息

最佳答案

数组不能是返回值,所以属性不能是数组类型。相反,您必须返回一个指针,因此将属性声明为指向数组元素类型的指针:

@property (readonly) float *mat;

将实例变量保持为 float mat[16],就像现在一样。然后实现访问器以返回指向数组的指针:

- (float *)mat {
return mat; // array decays to pointer automatically
}

或者,您可以直接为各个元素提供访问器:

- (float)matIndex:(NSUInteger)i {
// maybe check bounds here?
return mat[i];
}

这些方法的问题在于丢失了有关数组大小的信息,因此您可能希望将数组的大小放在宏或 const 变量中。如果您需要更面向对象的东西,请将数组设为 NSArray 并在其中存储 NSNumber

编辑:一种选择是将数组包装在 struct 中以保留大小信息,尽管您仍然可能希望通过引用传递它:

struct matrixf16 {
float f[16];
};
@interface Matrix4 : NSObject {
struct matrixf16 mat;
}
@property (readonly) struct matrixf16 *mat;

(此外,如果我猜对了大小为 16,因为它意味着要容纳 4×4 矩阵,为什么不使数组 float f[4][4]。)

关于objective-c - 我应该如何在 ObjC 中为 C 数组编写属性声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20136060/

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