我对使用 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/