比较类语法帮助中的对象;

Comparing an object within a class syntax help;

本文关键字:对象 帮助 语法 比较      更新时间:2023-10-16

我使用C++比目标c更有信心,我只是遇到了一个愚蠢的问题,即尝试比较两个对象(我正在构建的UniqueWord类)。我不断收到错误,期待一种类型;这是一个基本问题,但我也想解释一下我是如何做错的,这是我在C++写的。工作正常

private:
  vector <int> LineNumbers;
  string wordCatalog;// the current word in the line number
  int newIndex(const int);
public:
  UniqueWord(const string,const int);//creates the unique word object
  ~UniqueWord(void);
  void addLine(const int);
  static int compare(const UniqueWord&, const UniqueWord&);//my issue here
  string toString() const;

我的问题是在目标 C 中输入这个。这是我输入的内容Objective_c

@interface UniqueWord : NSObject
@property NSMutableArray *LineNumbers;
@property NSString *wordCatalog;
UniqueWord *UWord(const NSString*, const int);//creates a unique word object
int newIndex(const int);
-(void) addLine:(const int)line;
-(static NSInteger) compare:(UniqueWord *self)a with:(UniqueWord *self)b;//my issue
-(NSString*) toString;
@end

我真的很感激解释基本的语法规则(用现代语言解释)所以我下次不会有这个麻烦,谢谢。同样,我对目标C不是很有信心

附带说明一下,有人可以告诉我我是否是uniqueWord构造函数吗? 它说//创建一个唯一的单词对象

Objective-C 中没有static的方法 - 你需要一个类方法。将声明前面的-替换为+,如下所示:

+(NSInteger) compare:(UniqueWord *self)a with:(UniqueWord *self)b;

类方法类似于静态成员函数C++但由于方法调度在 Objective-C 中更动态地实现,因此您可以在派生类中为它们提供覆盖。

以上将编译。但是,这对 Objective-C 来说不是惯用的,因为 Cocoa 使用 NSComparisonResult 而不是 NSInteger 作为比较方法的返回类型:

+(NSComparisonResult) compare:(UniqueWord *self)a with:(UniqueWord *self)b;

此外,C++的构造函数通过指定的初始值设定项实现:这

UniqueWord *UWord(const NSString*, const int);

应如下所示:

-(id)initWithString:(NSString*)str andIndex:(NSInteger)index;

和/或像这样:

+(id)wordWithString:(NSString*)str andIndex:(NSInteger)index;

我认为更好的建议是实现一个实例compare:方法。 一个很好的答案在这里。

这样做是有充分理由的,具体来说,您要使用新compare:方法做的下一件事是对一组独特的单词进行排序。 @dasblinkenlight建议的类方法(语法无可挑剔)将迫使您编写自己的排序。 实例compare:提供了紧凑且可能更有效的替代方案:

[myArrayFullOfUniqueWords sortUsingSelector:@selector(compare:)];