在理解双指针概念及其应在何处使用时,我对此表示怀疑。我对这段代码进行了实验,发现我也可以使用按引用传递指针来代替双指针。
#include<iostream>
using namespace std;
void modify_by_value(int* );
void modify_by_refrence(int* &);
int a=4, b=5;
void main()
{
int *ptr = NULL;
ptr = &a;
cout << "*ptr before modifying by value: " << *ptr << endl;
modify_by_value(ptr);
cout << "*ptr after modifying by value: " << *ptr << endl;
cout << "*ptr before modifying by refrence: " << *ptr << endl;
modify_by_refrence(ptr);
cout << "*ptr after modifying by refrence: " << *ptr << endl;
}
void modify_by_value(int* ptr) //this function can change *ptr but not the ptr(address contained) itself;
{
ptr = &b;
}
void modify_by_refrence(int * &ptr) //this function has refrence and hence can modify the pointer;
{
ptr = &b;
}
Run Code Online (Sandbox Code Playgroud)
使用双指针代替引用的好处是什么?
“为什么使用对指针的引用而不是对指针的指针”?对于任何其他类型的变量,您将获得与询问“为什么使用指针而不是引用”的答案相同的答案...
基本上:
引用(指向指针或任何其他变量)很聪明,因为后面总应该有一个对象
指针(指向指针或任何其他变量)很聪明,因为它们可能是NULL(可选)
引用(对指针或任何其他变量)在C中不可用
引用(指向指针或任何其他变量)很聪明,因为它们可以用作对象(无需像指针那样取消引用,更轻松的语法和交易)
等等...
已经有很多帖子回答了这个问题:
| 归档时间: |
|
| 查看次数: |
4261 次 |
| 最近记录: |