問題描述
可能的重復:
指針變量和指針變量有什么區別C++中的引用變量?
路過有好處嗎在 C++ 中通過引用傳遞指針?
在這兩種情況下,我都達到了結果.那么什么時候一個比另一個更受歡迎呢?我們使用一個而不是另一個的原因是什么?
In both cases, I achieved the result. So when is one preferred over the other? What are the reasons we use one over the other?
#include <iostream>
using namespace std;
void swap(int* x, int* y)
{
int z = *x;
*x=*y;
*y=z;
}
void swap(int& x, int& y)
{
int z = x;
x=y;
y=z;
}
int main()
{
int a = 45;
int b = 35;
cout<<"Before Swap
";
cout<<"a="<<a<<" b="<<b<<"
";
swap(&a,&b);
cout<<"After Swap with pass by pointer
";
cout<<"a="<<a<<" b="<<b<<"
";
swap(a,b);
cout<<"After Swap with pass by reference
";
cout<<"a="<<a<<" b="<<b<<"
";
}
輸出
Before Swap
a=45 b=35
After Swap with pass by pointer
a=35 b=45
After Swap with pass by reference
a=45 b=35
推薦答案
引用在語義上如下:
T&<=>*(T * const)
const T&<=>*(T const * const)
T&&<=>[無 C 等價物]
(C++11)
與其他答案一樣,C++ 常見問題解答中的以下內容是單行答案:可能時引用,需要時使用指針.
As with other answers, the following from the C++ FAQ is the one-line answer: references when possible, pointers when needed.
優于指針的一個優點是您需要顯式轉換才能傳遞 NULL.不過還是有可能的.在我測試過的編譯器中,沒有一個會發出以下警告:
An advantage over pointers is that you need explicit casting in order to pass NULL. It's still possible, though. Of the compilers I've tested, none emit a warning for the following:
int* p() {
return 0;
}
void x(int& y) {
y = 1;
}
int main() {
x(*p());
}
這篇關于通過指針&通過引用傳遞的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!