There are certain rules when using references:
(1)A reference must be initialized when it is created. (Pointers can be initialized at any
time.)
(2)Once a reference is initialized to an object, it cannot be changed to refer to another
object. (Pointers can be pointed to another object at any time.)
(3)You cannot have NULL references. You must always be able to assume that a reference is
connected to a legitimate piece of storage.
改变指针自身的值
在C语言里,e.g
void f(int** ppi)
{
(*ppi)++;
}
int main()
{
int* i = 0;
cout<<"i = "<<i<<endl;//i = 0
f(&i);
cout<<"i = "<<i<<endl;//i = 1
return 0;
}
why?
需要自增一个指针(int *pi)所指向的内容时,可以(*pi)++
同理,自增指针(int *pi)自身的值时,指针同样有另外的指针(int **ppi)指向它,
可以(*ppi)++。
在C++里,可以使用pointer reference
void f(int* &pi)
{
pi++;
}
int main()
{
int* i = 0;
cout<<"i = "<<i<<endl;//i = 0
f(i);
cout<<"i = "<<i<<endl;//i = 1
return 0;
}
(1)A reference must be initialized when it is created. (Pointers can be initialized at any
time.)
(2)Once a reference is initialized to an object, it cannot be changed to refer to another
object. (Pointers can be pointed to another object at any time.)
(3)You cannot have NULL references. You must always be able to assume that a reference is
connected to a legitimate piece of storage.
改变指针自身的值
在C语言里,e.g
void f(int** ppi)
{
(*ppi)++;
}
int main()
{
int* i = 0;
cout<<"i = "<<i<<endl;//i = 0
f(&i);
cout<<"i = "<<i<<endl;//i = 1
return 0;
}
why?
需要自增一个指针(int *pi)所指向的内容时,可以(*pi)++
同理,自增指针(int *pi)自身的值时,指针同样有另外的指针(int **ppi)指向它,
可以(*ppi)++。
在C++里,可以使用pointer reference
void f(int* &pi)
{
pi++;
}
int main()
{
int* i = 0;
cout<<"i = "<<i<<endl;//i = 0
f(i);
cout<<"i = "<<i<<endl;//i = 1
return 0;
}