先看看代码:
#include<iostream> //代码片段1
using namespace std;
void GetResult(int * pInt)
{
cout<<pInt<<endl;
pInt=new int;
cout<<pInt<<endl;
*pInt=5;
}
int main()
{
int *pInt=NULL;
cout<<"before using function!"<<endl;
cout<<pInt<<endl;
GetResult(pInt);
cout<<"after using function!"<<endl;
cout<<pInt<<endl;
return 0;
}
程序结果:
before using function!
00000000
00000000
00035928
after using function!
00000000
#include<iostream> //代码片段2
using namespace std;
void GetResult(int * &pInt) //注意代码变化
{
cout<<pInt<<endl;
pInt=new int;
cout<<pInt<<endl;
*pInt=5;
}
int main()
{
int *pInt=NULL;
cout<<"before using function!"<<endl;
cout<<pInt<<endl;
GetResult(pInt);
cout<<"after using function!"<<endl;
cout<<pInt<<endl;
return 0;
}
程序结果:
before using function!
00000000
00000000
00035928
after using function!
00035928
原因:指针本身也是一个值而已,青年人网提示也就是本身与副本的关系。
想下,看哪个代码在return 0;前加cout<<*pInt<<endl;
责任编辑:小草