首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 计算机考试 > 等级考试 > 复习指导 >

C++基础解析二十二

2008-12-04 
指针本身也是一个值而已?

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

热点排行