基础:指针本身也是一个值而已?
来源:优易学  2011-11-22 10:49:49   【优易学:中国教育考试门户网】   资料下载   IT书店
  先看看代码:
  #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;

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训