Sri*_*nth 12 c++ pointers reference
在下面的代码,都amp_swap()和star_swap()似乎是在做同样的事情.那么为什么有人喜欢使用一个而不是另一个呢?哪一个是首选符号,为什么?或者只是品味问题?
#include <iostream>
using namespace std;
void amp_swap(int &x, int &y)
{
int temp = x;
x = y;
y = temp;
}
void star_swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int a = 10, b = 20;
cout << "Using amp_swap(): " << endl;
amp_swap(a, b);
cout << "a = " << a << ", b = " << b << endl;
cout << "Using star_swap(): " << endl;
star_swap(&a, &b);
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的时间!
也可以看看
Mar*_*ram 13
一个是使用引用,一个是使用指针.
我会使用带引用的那个,因为你不能传递一个NULL引用(而你可以传递一个NULL指针).
所以,如果你这样做:
star_swap(NULL, NULL);
Run Code Online (Sandbox Code Playgroud)
您的应用程序将崩溃.如果您尝试:
amp_swap(NULL, NULL); // This won't compile
Run Code Online (Sandbox Code Playgroud)
除非你有充分的理由使用指针,否则总是使用引用.
请参阅此链接:http://www.google.co.uk/search?q = references + vs +指针
| 归档时间: |
|
| 查看次数: |
1315 次 |
| 最近记录: |