引用VS指针
1.不存在空引用。引用必须连接到一块合法的内存。
2.一旦引用被初始化为一个对象,就不能被指向到另一个对象。指针可以在任何时候指向到另一个对象。
3.引用必须在创建时被初始化。指针可以在任何时间被初始化。
引用
格式:数据类型 &引用名 = 变量名
引用的本质在c++内部实现是一个指针常量
“别名”,引用与其代表的变量共享同一内存空间
引用并不是一种独立的数据类型,不占内存空间,它必须与某一种类型的变量相联系。在声明引用时,必须立即对它进行初始化,不能声明完成后再赋值。
引用在定义时需要添加&,在使用时不能添加&,使用时添加&表示取地址
为引用提供的初始值,可以是一个变量或者另一个引用。
引用可以作为函数参数,也可以作为返回值
返回值是引用,一般是用于迭代操作
注意:当返回值是引用时,不要返回局部变量。但是可以用static把他变成全局变量后,返回
int & test() { static int a=10; return a; } int main() { cout<<test();//10 return 0; }
引用整个数组(给数组取个别名)
1.指向n个元素的引用
int main()
{
int a[5]={1,2,3,4,5};
int (&b)[5]=a;
for(auto t:b)
cout<<t;
return 0;
}
2.typedef的方法
先给数组类型取别名,然后用新类型名定义一个变量
int main()
{
int a[5]={1,2,3,4,5};
typedef int TYPE_a[5];
TYPE_a &b=a;
for(auto t:b)
cout<<t;
return 0;
}
当函数返回值作为左值时,那么函数的返回值类型必须是引用
int & test()
{
static int a=10;
cout<<"a="<<a<<endl;
return a;
}
int main()
{
test()=100;
test();
return 0;
}
//输出a=10,a=100
指针的引用
例:一个指针要在函数内部开辟空间
错误示范
void test(char *q)
{
q=new char[12];//重新分配了地址q就不再指向p了
strcpy(q,"hello world");
cout<<q;//hello world
}
int main()
{
char *p=NULL;
test(p);
cout<<*p;//没有输出
return 0;
}
c语言--双重指针
void test(char **q)
{
*q=new char[12];
strcpy(*q,"hello world");
cout<<*q<<endl;
}
int main()
{
char *p=NULL;
test(&p);
cout<<p<<endl;
return 0;
}
C++--指针的引用
void test(char* &q)
{
q=new char[12];
strcpy(q,"hello world");
cout<<q<<endl;
}
int main()
{
char *p=NULL;
test(p);
cout<<p<<endl;
return 0;
}