我有一个我想在类中以典型的C 样式来声明和使用的函数。
来自.mm文件的假设示例定义:
float MyClass::getRectArea(float width, float height){
return width*height;
}
如何在Objective-C类标题/.H文件中声明此功能?
@interface MyClass
//???
@end
您可以像在C 中一样将其写成一个函数 - 只有它不会成为类的一部分,因为函数不在Objective-C中的类别中。如果您希望它成为一堂课的一部分,则可以将其作为类方法作为:
的类方法+ (float)rectAreaWithWidth:(float)width height:(float)height {
return width * height;
}
我可能不会将其作为实例方法,正如另一个答案中所建议的那样,因为它确实与特定对象值无关 - 这是其参数的纯粹函数。
您可以将其声明为
-(float)getRectArea:(float)width getheight:(float)height;
然后在.m文件中,您可以将其定义为
-(float)getRectArea:(float)width getheight:(float)height {
return width*height;
}
您可以按以下方式称呼它
float area = [self getRectArea:5.0 getheight:4.0];
有关更多详细信息和说明,请参见目标C
如果您希望myClass成为C 对象,那么您将像通常使用C 一样创建标头。
myclass.h
class MyClass
{
public:
float getRectArea(float width, float height);
};