感觉指针和引用之间的奇妙,写了两端代码以搞清楚指针引用和引用的用法
读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;