引用与指针有什么区别?
1) 引用必须被初始化,指针不必。所以不存在指向空值的引用,但是存在指向空值的指针
2) 引用初始化以后不能被改变,指针可以改变所指的对象。
传递指针本质上传递的也是拷贝的副本,只不过副本是地址。
保护传递给函数的数据不在函数中被改变
指针:
#include<iostream> using namespace std; void test(int *p) { int a=1; p=&a; cout<<p<<" "<<*p<<endl; } int main(void) { int *p=NULL; test(p); if(p==NULL) cout<<"指针p为NULL"<<endl; return 0; }
输出结果:0xffffdcb4e0 1
指针p为NULL
引用:
#include<iostream> using namespace std; void test(int *&p) { int a=1; p=&a; cout<<p<<" "<<*p<<endl; } int main(void) { int *p=NULL; test(p); if(p!=NULL) cout<<"指针p不为NULL"<<endl; return 0; }
输出结果:0xffffdd1320 1
指针p不为NULL
// readXml.cpp : 定义控制台应用程序的入口点。 // #include <iostream> #include <string> #include <string.h> using namespace std; class a { public: int i; a() { i = 4; } }; class b { public: a j; public: a& geta(){ return j; } void seta(int s) { j.i = s; } }; int main(int argc, char** argv) { b h; h.seta(7); a &f= h.geta(); f.i = 12; cout << f.i << " " << h.j.i<<endl; int q = 2; int &w = q; w = 3; cout << q << endl; system("pause"); }
只有函数返回引用类型,调用也是引用类型,引用才能行。变量则只需调用时是引用就行。
引用必须在声明时就赋值。
int get(int& a)
{
a = a + 1;
return a;
}
int main(int argc, char** argv)
{
int i = 11;
int j = get(i);
cout << j << " "<< i << endl;
system("pause");
}
返回两个12