比较类语法帮助中的对象;
Comparing an object within a class syntax help;
我使用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:)];
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 我需要帮助以连续的方式将对象的字段正确写入文件
- C++ RapidJson 帮助反序列化数组对象
- IE 探索 11 < c++ ATL COM 浏览器帮助程序对象(加载项)来替换 DOM 中的文本
- 具有查找表的可选帮助的对象查找,如果未使用,则必须对其进行优化
- 比较类语法帮助中的对象;
- 如何在 Windows11(x7) 上使用 EPM 一次将 64 个浏览器帮助程序对象 dll 注册到 IE7 中
- 面向对象C++帮助?出于某种原因,对象变量的输出返回数值数组位置而不是实际值
- 如何在 c++ 中将包含指针变量的对象写入和读取到文件中?帮助我使用以下代码
- 简单的多线程帮助?C++、等待单一对象和同步
- 需要帮助在类中创建对象,并为成员函数赋值
- 对象指针的矢量,一般帮助和混淆
- 帮助在C++中设置/构造类和对象中的静态数组大小
- 语法帮助.模板函数对象中的模板运算符()