Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
Are there benefits of passing by pointer over passing by reference in C++?Băng qua con trỏ & Vượt qua tham chiếu
Trong cả hai trường hợp, tôi đạt được kết quả. Vì vậy, khi nào được ưa thích hơn người kia? Những lý do chúng tôi sử dụng cái nào khác?
#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\n";
cout<<"a="<<a<<" b="<<b<<"\n";
swap(&a,&b);
cout<<"After Swap with pass by pointer\n";
cout<<"a="<<a<<" b="<<b<<"\n";
swap(a,b);
cout<<"After Swap with pass by reference\n";
cout<<"a="<<a<<" b="<<b<<"\n";
}
Output
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
http://stackoverflow.com/questions/114180/pointer-vs-reference –
[Có lợi ích khi chuyển qua con trỏ qua khi tham chiếu trong C++ không?] (Http://stackoverflow.com/q/334856/ 187543) – cpx