执行C ++的“const方法”的近似,存在为Objective-C? [英] Does an approximation of C++'s "const methods" exist for Objective-C?

查看:123
本文介绍了执行C ++的“const方法”的近似,存在为Objective-C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道是否有任何接受的做法来近似Objective-C中的C ++的'const方法'。 (C / C ++背景下的新语言)

Wondering if there's any accepted practice for approximating C++'s 'const methods' in Objective-C. (new to the language from a C/C++ background)

例如:

class Foo {
  public:
     void canChangeMemberVars(void);
     char* asString(void) const;
};

asString()get a const this 指针,所以即使你走向流氓,并决定使用实例的成员,它将无法工作。从文档的角度来看,我发现标签方法const是非常有用的。

"asString()" gets a const this pointer, so even if you go rogue and decide to muck around with the instance's members it won't work. I find labelling methods as const to be quite useful from a documentation standpoint for libraries I write.

我正在编写一个Objective-C类库,发现自己想要能够使用特定的方法const,并想知道是否有任何语言技巧来实现这一点。

I'm in the midst of writing an Objective-C class library, and find myself wanting to be able to make specific methods const, and wondering if there's any language tricks to achieve this.

总结

在一天结束时,是唯一的方法来实现类似的功能,因素类在Mutable和Immutable版本?

At the end of the day is the the only way to achieve similar functionality to factor classes in Mutable and Immutable versions? Making a simple note in the comments for each method isn't rigid enough for my purposes.

推荐答案

是的,你唯一的选择if你想有一个类,有时可以突变,有时不能是使类的可变和不可变版本。你会注意到这是苹果在Cocoa(NSArray,NSSet,NSDictionary,NSString等)的做法 - 遵循苹果的惯例通常是最好的方式。

Yes, your only option if you want to have a class that sometimes can be mutated and sometimes can't is to make mutable and immutable versions of the class. You'll notice this is how Apple does it in Cocoa (NSArray, NSSet, NSDictionary, NSString, etc.) — following Apple's conventions is usually the best way to go.

Objective-C甚至没有一个 const 对象的概念。即使您声明了一个对象指针 const ,也不会阻止您对设置变量的对象调用方法。

Objective-C really doesn't even have a concept of a const object. Even if you do declare an object pointer const, that doesn't prevent you from calling methods on the object that set variables.

这篇关于执行C ++的“const方法”的近似,存在为Objective-C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆