The most important difference between pointers in C and those in C++ is that C++ is a more strongly typed language.This stands out where void * is concerne.
代码:
bird * b;
rock * r;
void * v;
v=r;
b=v;//这两个赋值在C编译器通过,在C++编译器不通过
void * 在C中表示指向任意的类型. 在C++中表示指向void类型.
A reference (&) is like a const pointer that is automatically dereferenced.There are certain rules when using references.
1.A reference must be initialized when it is created.(Pointers can be intialized at any time).
2.Once a reference is initialized to an object,it can not be changed to refer to another object.
(Pointers can be pointed to another object at any time).
3.you can not have NULL reference.
把引用认为是一个对象的别名,上面规则就好理解了.
下面看一段代码的汇编来理解
#include <iostream>
using namespace std;
int* f1(int * px)
{
(*px)++;
return px;
}
int& g1(int & rx)
{
rx++;
return rx;
}
int main()
{
int a=1;
f1(&a);
g1(a);
return 0;
}
总结:从此例汇编层来看,引用和指针是没有区别的.
那我就有一个地方想不明白了
#include <iostream>
using namespace std;
int main()
{
int a=3;
int *pa=&a;
int & ra=a;
cout<<&pa<<endl;
cout<<&ra<<endl;
cout<<&a<<endl;
return 0;
}
结果:
0012FF78
0012FF7C
0012FF7C
这两个输出为什么不同?
继续跟踪汇编
1: #include <iostream>
2:
3: using namespace std;
4:
5: int main()
6:
7: {
00401250 push ebp
00401251 mov ebp,esp
00401253 sub esp,54h//(54h-40h)/04h=20/4=5
00401256 push ebx
00401257 push esi
00401258 push edi
00401259 lea edi,[ebp-54h]
0040125C mov ecx,15h
00401261 mov eax,0CCCCCCCCh
00401266 rep stos dword ptr [edi]
8:
9: int a=3;
00401268 mov dword ptr [ebp-4],3//第一个局部变量a
10:
11: int *pa=&a;
0040126F lea eax,[ebp-4]
00401272 mov dword ptr [ebp-8],eax //第二个局部变量pa
12:
13: int & ra=a;
00401275 lea ecx,[ebp-4]
00401278 mov dword ptr [ebp-0Ch],ecx // 第三个局部变量ra
14: int * pb=&a;
0040127B lea edx,[ebp-4]
0040127E mov dword ptr [ebp-10h],edx//第四个局部变量pb
15: pb=&ra;
00401281 mov eax,dword ptr [ebp-0Ch]
00401284 mov dword ptr [ebp-10h],eax
16: int ** pc=&pa;
00401287 lea ecx,[ebp-8]//第五个局部变量
0040128A mov dword ptr [ebp-14h],ecx
17:
18:
19: return 0;
0040128D xor eax,eax
20:
21: }
0040128F pop edi
00401290 pop esi
00401291 pop ebx
00401292 mov esp,ebp
00401294 pop ebp
00401295 ret
总结:
搞明白了,引用其实就是一个指针,只是编译器会自动对它解析,并进行代码优化.
也就是 A reference (&) is like a const pointer that is automatically dereferenced.
所以上面的代码
cout<<&ra<<endl;编译器对它做了转化 cout<< &(*ra)<<endl;