1

我使用 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;

我的问题是在Objective 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

我非常感谢解释基本的语法规则(用现代语言解释),所以下次我不会遇到这个麻烦,谢谢。再说一次,我对 Objective C 不是很有信心

在旁注中,有人可以告诉我,如果我是 uniqueWord 构造函数,对吗?它说//创建一个唯一的单词对象

4

2 回答 2

3

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++ 的构造函数是通过指定的初始化器实现的:this

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

应该是这样的:

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

和/或像这样:

+(id)wordWithString:(NSString*)str andIndex:(NSInteger)index;
于 2013-11-10T17:49:03.440 回答
1

I think better advice is to implement an instance compare: method. A good answer is here.

There's good reason to do this, specifically, the very next thing you'll want to do with your new compare: method is sort an array of unique words. The class method that @dasblinkenlight suggests (with impeccable syntax) will force you to write you're own sort. An instance compare: provides compact and probably much more efficient alternative:

[myArrayFullOfUniqueWords sortUsingSelector:@selector(compare:)];
于 2013-11-10T18:15:23.553 回答