c++ - 在类语法帮助中比较对象;

标签 c++ objective-c class object

我对使用 C++ 比使用 objective 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 构造函数是否正确?它说//创建一个独特的单词对象

最佳答案

在 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;

关于c++ - 在类语法帮助中比较对象;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19892932/

相关文章:

c++ - 声明为 consts 的函数 args 随定义变为非常量

c++ - 从基类继承两次时如何修复 "error: no matching function for call to"

带有或不带有实例变量的 Objective-C 属性

c++ - 对字符数组中的单词进行排序

python - 以编程方式在嵌入式 python 3 中定义包结构

objective-c - 具有自定义 View 的 NSMenuItem 不会更新

iphone - 按字符串值对字符串的 NSMutableArray 进行排序

iphone - NSInputStream 的例子?

java - 为什么JVM不支持强制类/类加载器卸载?

python - 通过字典调用类方法