2011-09-13 37 views
-1

可能重複:
What's your preferred pointer declaration style, and why?
In C, why is the asterisk before the variable name, rather than after the type?
What makes more sense - char* string or char *string?Objective-C對象實例聲明中的星號:由Object還是由實例?

當聲明在Objective-C的對象的新實例,它使任何區別,你把星號?

這只是個人喜好的問題嗎?

NSString* string = @""; 

NSString *string = @""; 
+1

這已經被問* *很多次才:http://stackoverflow.com/questions/180401/c-asterisks-and-指針http:// stackoverflow。com/questions/2660633/declaring-pointers-asterisk-on-the-the-the-the-the-space-between-the-type-a http://stackoverflow.com/questions/558474/what-makes -more-sense-char-string-or-char-string http://stackoverflow.com/questions/377164/whats-your-preferred-pointer-declaration-style-and-why http://stackoverflow.com/questions/398395/in-c-why-the-as-the-as-the-variable-name-before-the-after-the-type這裏僅舉幾例 –

+0

我相信這個問題仍然很重要,因爲它很可能被發現通過可能不知道使用短語「C指針」的Objective-C初學者。 – andyvn22

+0

@Adam Rosenfield - 你更喜歡哪一個? – MJN

回答

11

它不會有所作爲,但也有把它在每個地方很好的理由:

  • 這是有道理的把它附近該類,因爲這使它感覺像一個類型:NSString*,一個指向字符串的指針。明智的。

  • 將它放在變量附近是有意義的,因爲這就是實際發生的事情:*是取消引用。當您取消引用您的指針string時,會得到NSString*stringNSString。明智的。

您可能想要去後者,因爲這是編譯器的思維方式,所以:NSString* oneString, anotherString將無法​​正常工作,而NSString *oneString, *anotherString是正確的。

1

它不會讓你把這個指針符號的區別。如果你在單行中聲明瞭多個對象,你可以像NSString * str1,* str2那樣進行。所以它更適合把星號貼近對象。我更喜歡它接近對象實例。

2

這只是一個偏好問題。將*放在類型旁邊強調它是類型的一部分,即「指向NSString的指針」。但是,這通常會被忽視,因爲它忽略了*與最近的變量名關聯的事實,而不是類型名稱。例如,以下不起作用:

NSString* a = @"string1", b = @"string2 

這是因爲a是一個指針,但b不是。

把*放在變量名旁邊,在我看來,更多的是C/C++約定,因爲它強調*和變量名一起的行爲就像變量一樣。

就我個人而言,我在*的兩側放置了一個空格。

是問同樣的事情的另一個問題是在這裏:

Declaring pointers; asterisk on the left or right of the space between the type and name?

相關問題