누구는 C++에서매개 변수에서 '&'를 함수에 배치 할 위치는 어디입니까?
void fun(MyClass &mc);
및
void fun(MyClass& mc);
의 차이점은 무엇인지 말씀해 주시겠습니까?
누구는 C++에서매개 변수에서 '&'를 함수에 배치 할 위치는 어디입니까?
void fun(MyClass &mc);
및
void fun(MyClass& mc);
의 차이점은 무엇인지 말씀해 주시겠습니까?
주어진대로. 원래
는 C 허용 것 :int x, *y;
는 둘 모두 int
, x
및 포인터가 int로 y
를 선언하려면.
따라서 유형 정의의 일부 (포인터가되는 비트)는 다른 부분과 분리 될 수 있습니다.
C++이 (가)이 도매가를 복사했습니다.
다음은 참조가 추가 된 곳이며 *
이 아닌 &
을 제외하고 유사한 선언 스타일을가집니다. 즉, 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
는 "전형적인 C++"스타일과 일치합니다.
컴파일러에는 아무런 차이가 없습니다.
첫 번째는 일반적인 C- 구문에 더 가깝고, 후자는 C + + - ish입니다.
이 내용은 대부분의 소개 자료에서 설명됩니다. –
이 질문을 구문 질문이라는 것을 깨닫기 위해이 질문을 3 번 읽어야했습니다. –
가능한 [C++ 참조 구문] 복제본 (http://stackoverflow.com/questions/4515306/c-reference-syntax) –