指针引用与引用

发表于:2007-05-25来源:作者:点击数: 标签:指针用之间的感觉引用
感觉指针和引用之间的奇妙,写了两端代码以搞清楚指针引用和引用的用法 读C++primer 一书 感觉指针和引用之间的奇妙,写了两端代码以搞清楚指针引用和引用的用法 #include iostream using namespace std; int main(void) { int ival1 = 1024 ; int *pival1

  感觉指针和引用之间的奇妙,写了两端代码以搞清楚指针引用和引用的用法

读C++primer 一书

感觉指针和引用之间的奇妙,写了两端代码以搞清楚指针引用和引用的用法

#include <iostream>

using namespace std;

int main(void)
{
 int  ival1 = 1024 ;
 int *pival1 = &ival1;   //ival的指针
 int *& pi1 = pival1;   //ival的指针的引用
   
 int  ival2 = 2048;
 int *pival2 = &ival2;   //iva2的指针
 int *& pi2 = pival2;   //iva2的指针的引用

 cout<<"ival1: "<<ival1<<endl;
 cout<<"pival1:"<<pival1<<endl;
 cout<<"pi1:   "<<pi1<<endl;
 cout<<"ival2: "<<ival2<<endl;
 cout<<"pival2:"<<pival2<<endl;
 cout<<"pi2:   "<<pi2<<endl;
  
 cout<<"-------------------"<<endl;

 *pi1 = *pi2;    //解除指针引用
 
 cout<<"ival1: "<<ival1<<endl;
 cout<<"pival1:"<<pival1<<endl;
 cout<<"pi1:   "<<pi1<<endl;
 cout<<"ival2: "<<ival2<<endl;
 cout<<"pival2:"<<pival2<<endl;
 cout<<"pi2:   "<<pi2<<endl;
 
 /*out put
 ival1: 1024
 pival1:0xbfffe6a4
 pi1:   0xbfffe6a4
 ival2: 2048
 pival2:0xbfffe698
 pi2:   0xbfffe698
 -------------------
 ival1: 2048
 pival1:0xbfffe6a4
 pi1:   0xbfffe6a4
 ival2: 2048
 pival2:0xbfffe698
 pi2:   0xbfffe698
   
 */
 //输出说明*pi1 = *pi2;
 //之间的赋值并未改变指针引用的值,即地址的值
 //而是改变了引用对象的值
}

///////////////////////////////////////////////////////////////////////////////////

#include <iostream>

using namespace std;

int main(void)
{
 int  ival1 = 1024 ;
 int *pival1 = &ival1;
 int *& pi1 = pival1;
   
 int  ival2 = 2048;
 int *pival2 = &ival2;
 int *& pi2 = pival2;

 cout<<"ival1: "<<ival1<<endl;
 cout<<"pival1:"<<pival1<<endl;
 cout<<"pi1:   "<<pi1<<endl;
 cout<<"ival2: "<<ival2<<endl;
 cout<<"pival2:"<<pival2<<endl;
 cout<<"pi2:   "<<pi2<<endl;
  
 cout<<"-------------------"<<endl;
   
 pi1 = pi2;
 cout<<"ival1: "<<ival1<<endl;
 cout<<"pival1:"<<pival1<<endl;
 cout<<"pi1:   "<<pi1<<endl;
 cout<<"*pi1:  "<<*pi1<<endl;
 
 cout<<"ival2: "<<ival2<<endl;
 cout<<"pival2:"<<pival2<<endl;
 cout<<"pi2:   "<<pi2<<endl;
 cout<<"*pi2:  "<<*pi2<<endl;       
 
 /*out put
 ival1: 1024
 pival1:0xbffff5a4
 pi1:   0xbffff5a4
 ival2: 2048
 pival2:0xbffff598
 pi2:   0xbffff598
 -------------------
 ival1: 1024
 pival1:0xbffff598
 pi1:   0xbffff598
 *pi1:  2048
 ival2: 2048
 pival2:0xbffff598
 pi2:   0xbffff598
 *pi2:  2048
 */  
 //输出说明,指针引用之间的赋值只改变指针的值
 //引用对象的值没有改变
}

原文转自:http://www.ltesting.net

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)