指针变量和引用变量之间的区别是什么?
当前回答
这个程序可能有助于理解问题的答案。这是一个引用“j”和指向变量“x”的指针“ptr”的简单程序。
#include<iostream>
using namespace std;
int main()
{
int *ptr=0, x=9; // pointer and variable declaration
ptr=&x; // pointer to variable "x"
int & j=x; // reference declaration; reference to variable "x"
cout << "x=" << x << endl;
cout << "&x=" << &x << endl;
cout << "j=" << j << endl;
cout << "&j=" << &j << endl;
cout << "*ptr=" << *ptr << endl;
cout << "ptr=" << ptr << endl;
cout << "&ptr=" << &ptr << endl;
getch();
}
运行程序并查看输出,您就会明白。
另外,抽出10分钟观看以下视频:https://www.youtube.com/watch?v=rlJrrGV0iOg
其他回答
除非我需要以下任何一项,否则我会使用参考资料:
空指针可以用作哨兵价值,通常是一种廉价的方式避免函数重载或使用嘘声。你可以在指针上做算术。例如,p+=偏移量;
如果遵循传递给函数的参数的约定,则可以使用引用和指针之间的差异。Const引用用于传递到函数中的数据,指针用于传递出函数的数据。在其他语言中,您可以使用诸如In和out之类的关键字来明确表示这一点。在C++中,您可以(按照约定)声明等价的。例如
void DoSomething(const Foo& thisIsAnInput, Foo* thisIsAnOutput)
{
if (thisIsAnOuput)
*thisIsAnOutput = thisIsAnInput;
}
使用引用作为输入和指针作为输出是Google风格指南的一部分。
不能像指针一样取消引用,当取消引用时,
引用和指针都是通过地址工作的。。。
so
你可以这样做
int*val=0xDEADBEEF;*val是0xDEADBEEF的值。
你不能这样做int&V=1;
*不允许使用val。
你忘记了最重要的部分:
带指针的成员访问使用->使用引用的成员访问。
foo.bar明显优于foo->bar,就像vi明显优于Emacs一样:-)
简单地说,我们可以说引用是变量的替代名称,指针是保存另一个变量地址的变量。例如
int a = 20;
int &r = a;
r = 40; /* now the value of a is changed to 40 */
int b =20;
int *ptr;
ptr = &b; /*assigns address of b to ptr not the value */