在指向对象的指针之前,const说明符做什么? [英] What does the const specifier do, before a pointer to object?

查看:88
本文介绍了在指向对象的指针之前,const说明符做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的C字符串:

If I have a C-string like this:

const char* str= "hello";

我很清楚我不能更改字符串的任何字符,因为指针是const.
但是如果我有这个:

I know well that I can't change any character of the string because the pointer is const.
But if I have this:

- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location

我仍然可以使用其方法来改变对象状态.
如果指针指向NSMutableString,我仍然可以对其进行突变.
那么const代表什么呢?

I can still mutate the object state using it's methods.
If the pointer is to a NSMutableString, I'm still able to mutate it.
Then what does the const stand for?

推荐答案

在该方法声明中,location是指向常量CLLocation的指针.但是,当您向location对象发送消息时,const -ness不会保留;处理消息的方法将self视为非const对象. (请注意,这不同于C ++,后者支持const成员函数,其中this是指向常量对象的指针.)

In that method declaration, location is a pointer to a constant CLLocation. But when you send a message to the location object, the const-ness is not preserved; the method that handles the message sees self as a non-const object. (Note that this is different than C++, which supports const member functions where this is a pointer to a constant object.)

因此该声明中的const并不是特别有用.也许它是由习惯于C ++做事的人编写的.

So the const in that declaration is not particularly useful. Perhaps it was written by someone used to the C++ way of doing things.

当您看到const附加在Objective-C中的对象指针上时,通常是这样的:

When you do see const attached to an object pointer in Objective-C, it is usually like this:

extern NSString * const SomeConstantString;

这将SomeConstantString声明为指向某些非常量对象(在本例中为NSString)的常量指针.指针本身是常量,因此您的程序无法将SomeConstantString更改为指向其他NSString对象.

This declares SomeConstantString as a constant pointer to some non-constant object (in this case, an NSString). The pointer itself is constant, so your program can't change SomeConstantString to point to some other NSString object.

这篇关于在指向对象的指针之前,const说明符做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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