读书人

C++基础解析二十二

发布时间: 2008-12-04 16:03:09 作者: liuhuituzi

看代码:
  #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;

3COME考试频道为您精心整理,希望对您有所帮助,更多信息在http://www.reader8.net/exam/

读书人网 >复习指导

热点推荐