指针变量和引用变量之间的区别是什么?
当前回答
这是基于教程。所写内容更清楚:
>>> The address that locates a variable within memory is
what we call a reference to that variable. (5th paragraph at page 63)
>>> The variable that stores the reference to another
variable is what we call a pointer. (3rd paragraph at page 64)
简单地记住,
>>> reference stands for memory location
>>> pointer is a reference container (Maybe because we will use it for
several times, it is better to remember that reference.)
此外,我们可以参考几乎任何指针教程,指针是指针算术支持的对象,它使指针类似于数组。
看看下面的陈述,
int Tom(0);
int & alias_Tom = Tom;
alias_Tom可以理解为变量的别名(与typedef不同,typedef是一种类型的别名)Tom。忘记这种说法的术语也是可以的,即创建一个对汤姆的引用。
其他回答
将指针视为名片:
它让你有机会联系某人它可以是empy它可能包含错误或过时的信息你不确定上面提到的某人还活着你不能直接与卡片通话,你只能用它打电话给某人也许有很多这样的卡片
将推荐人视为与某人的主动通话:
你很确定你联系过的人还活着您可以直接通话,无需额外通话你很确定你不会和一个空地方或一块垃圾说话你不能确定你是唯一一个当前正在与此对象交谈的人
指针和引用之间的差异
指针可以初始化为0,而引用不能初始化。事实上,引用也必须引用对象,但指针可以是空指针:
int* p = 0;
但我们不能有int&p=0;以及int&p=5;。
事实上,要正确执行此操作,我们必须首先声明并定义了一个对象,然后才能引用该对象,因此前面代码的正确实现将是:
Int x = 0;
Int y = 5;
Int& p = x;
Int& p1 = y;
另一个重要的点是,我们可以在不初始化的情况下声明指针,但是在引用的情况下,不能这样做,因为引用必须始终引用变量或对象。然而,这样使用指针是有风险的,因此通常我们检查指针是否确实指向某个对象。在引用的情况下,不需要这样的检查,因为我们已经知道在声明期间引用对象是强制性的。
另一个区别是指针可以指向另一个对象,但是引用总是引用同一个对象
Int a = 6, b = 5;
Int& rf = a;
Cout << rf << endl; // The result we will get is 6, because rf is referencing to the value of a.
rf = b;
cout << a << endl; // The result will be 5 because the value of b now will be stored into the address of a so the former value of a will be erased
另一点:当我们有一个类似STL模板的模板时,此类类模板将始终返回一个引用,而不是指针,以便使用运算符[]轻松读取或分配新值:
Std ::vector<int>v(10); // Initialize a vector with 10 elements
V[5] = 5; // Writing the value 5 into the 6 element of our vector, so if the returned type of operator [] was a pointer and not a reference we should write this *v[5]=5, by making a reference we overwrite the element by using the assignment "="
我对引用和指针有一个类比,将引用看作对象的另一个名称,将指针看作对象的地址。
// receives an alias of an int, an address of an int and an int value
public void my_function(int& a,int* b,int c){
int d = 1; // declares an integer named d
int &e = d; // declares that e is an alias of d
// using either d or e will yield the same result as d and e name the same object
int *f = e; // invalid, you are trying to place an object in an address
// imagine writting your name in an address field
int *g = f; // writes an address to an address
g = &d; // &d means get me the address of the object named d you could also
// use &e as it is an alias of d and write it on g, which is an address so it's ok
}
如果你不熟悉以抽象的甚至学术的方式学习计算机语言,那么语义上的差异可能会显得深奥难懂。
在最高级别上,引用的概念是它们是透明的“别名”。你的计算机可能会使用一个地址来使它们工作,但你不必担心:你应该将它们视为现有对象的“另一个名称”,语法反映了这一点。它们比指针更严格,因此编译器可以在您将要创建悬挂引用时比在您将创建悬挂指针时更可靠地警告您。
除此之外,指针和引用之间当然还有一些实际差异。使用它们的语法明显不同,您不能“重新定位”引用、引用虚无或引用指针。
指针是保存另一个变量的内存地址的变量,其中引用是现有变量的别名。(已存在变量的另一个名称)
1.指针可以初始化为:
int b = 15;
int *q = &b;
OR
int *q;
q = &b;
其中作为参考,
int b=15;
int &c=b;
(在一个步骤中声明和初始化)
指针可以分配给null,但引用不能可以对指针执行各种算术运算,而没有所谓的参考算术。指针可以重新分配,但引用不能指针在堆栈上有自己的内存地址和大小,而引用共享相同的内存地址