其他分享
首页 > 其他分享> > 指针和引用(pointer and reference),传值和传址

指针和引用(pointer and reference),传值和传址

作者:互联网

pass by adress

pass by referencepass by pointer的共同点都在于传址,都是对于对象的地址的复制,而不会对对象进行产生副本的操作。

pass by reference 和pass by pointer 的区别:

1.首先是在语法上的小区别。

2.其次更重要的是
1)pointer可能指向一个实际对象,因为其可能为nullptr,这是在pointer中必须要单独考虑的。
比如这句话:

if(!vec){
cout<<"The pointer is nullptr."<<endl;
return ;}

这是很有必要的

2)reference是不一样的,它是一定会对应一个实际的对象,并且不可更改。

pass by value

pass by value是对对象的一个复制操作,会产生一个新的对象副本,当函数结束时,从程序堆栈中进行回收

void display (vector <int>*vec){
if(!vec){
cout<<"The pointer is nullptr."<<endl;
return ;}
for(int  i=0;i<vec->size();i++)
cout<<vec[i]<<" ";
}
void display(vector<int>&vec)
{
for(int j=0;j<vec.size();j++)
cout<<vec[j]<<" ";
}

在对于传递内置类型时,不要采用传址方式。
传址机制主要用于传递类对象(class object)

标签:传址,reference,对象,vec,pass,pointer
来源: https://www.cnblogs.com/FJCLJ/p/16532015.html