2012-09-05 10 views
5

किसी को भी मुझे बता सकते हैं क्या सी ++ मेंकिसी फ़ंक्शन में पैरामीटर में '&' कहां रखा जाए?

void fun(MyClass &mc); 

और

void fun(MyClass& mc); 

के बीच का अंतर है?

+1

मुझे यकीन है कि यह सबसे प्रारंभिक सामग्री में समझाया गया है। –

+1

मुझे यह समझने के लिए 3 बार इस प्रश्न को पढ़ना पड़ा कि यह एक वाक्यविन्यास प्रश्न है। –

+0

[सी ++ संदर्भ वाक्यविन्यास] का संभावित डुप्लिकेट (http://stackoverflow.com/questions/4515306/c-reference-syntax) –

उत्तर

8

जैसा कि कोई भी नहीं दिया गया है।

मूल रूप से, सी की अनुमति होगी:

int x, *y; 

घोषित दोनों एक int, x और एक सूचक int करने के लिए, y करने के लिए।

इसलिए प्रकार की परिभाषा का हिस्सा - बिट जो इसे पॉइंटर बनाता है - को दूसरे भाग से अलग किया जा सकता है।

सी ++ ने इस थोक की प्रतिलिपि बनाई।

फिर संदर्भ जहां कहा गया, और * के बजाय & को छोड़कर उन्हें घोषणा की एक समान शैली मिली। इसका मतलब था कि MyClass &mc और MyClass& mc दोनों की अनुमति थी।

विकल्प पर जब यह * की बात आती है, Strousup wrote:

Both are "right" in the sense that both are valid C and C++ and both have exactly the same meaning. As far as the language definitions and the compilers are concerned we could just as well say "int*p;" or "int * p;"

The choice between "int* p;" and "int *p;" is not about right and wrong, but about style and emphasis. C emphasized expressions; declarations were often considered little more than a necessary evil. C++, on the other hand, has a heavy emphasis on types.

A "typical C programmer" writes "int *p;" and explains it "*p is what is the int" emphasizing syntax, and may point to the C (and C++) declaration grammar to argue for the correctness of the style. Indeed, the * binds to the name p in the grammar.

A "typical C++ programmer" writes "int* p;" and explains it "p is a pointer to an int" emphasizing type. Indeed the type of p is int*. I clearly prefer that emphasis and see it as important for using the more advanced parts of C++ well.

The critical confusion comes (only) when people try to declare several pointers with a single declaration:

int* p, p1; // probable error: p1 is not an int*

Placing the * closer to the name does not make this kind of error significantly less likely.

int *p, p1; // probable error?

Declaring one name per declaration minimizes the problem - in particular when we initialize the variables. People are far less likely to write:

int* p = &i; int p1 = p; // error: int initialized by int*

And if they do, the compiler will complain.

Whenever something can be done in two ways, someone will be confused. Whenever something is a matter of taste, discussions can drag on forever. Stick to one pointer per declaration and always initialize variables and the source of confusion disappears. See The Design and Evolution of C++ for a longer discussion of the C declaration syntax.

विस्तार करने पर, जब यह & की बात आती है, MyClass& mc "ठेठ सी ++" शैली से मेल खाता।

5

कंपाइलर में कोई अंतर नहीं है।

पहला सामान्य सी-सिंटैक्स के करीब है, बाद वाला सी ++ - आईएसएच है।