首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++中指针函数引用的有关问题,求解

2012-09-07 
C++中指针函数引用的问题,求解为什么这两个程序输出不一样啊?我只是改了一句嘛?1.#include iostreamusin

C++中指针函数引用的问题,求解
为什么这两个程序输出不一样啊?我只是改了一句嘛?
1.
#include <iostream>  
using namespace std;  
  
int *&FuncTest(int *&p,int &m)  
{  
  p=&m;  
  return p;  
}  
  
int main(void)  
{  
  int nN=12;int nM=122;  
  int *np=&nN;  
  
  cout<<"n地址:"<<&nN<<" m地址:"<<&nM<<endl;  
  cout<<"初始p指向:"<<np<<endl;  
  cout<<*FuncTest(np,nM)<<endl<<*np<<endl;  
  cout<<np<<endl;  
  cout<<"m值:"<<nM<<endl;  
}  

2.#include <iostream>  
using namespace std;  
  
int *&FuncTest(int *&p,int &m)  
{  
  p=&m;  
  return p;  
}  
  
int main(void)  
{  
  int nN=12;int nM=122;  
  int *np=&nN;  
  
  cout<<"n地址:"<<&nN<<" m地址:"<<&nM<<endl;  
  cout<<"初始p指向:"<<np<<endl;  
  cout<<*FuncTest(np,nM)<<endl;
cout<<*np<<endl;  
  cout<<np<<endl;  
  cout<<"m值:"<<nM<<endl;  
}

[解决办法]
目测是因为求值顺序点引起的。
http://topic.csdn.net/u/20110826/09/601ebe9c-c2ae-4d63-a4e2-506c618bb654.html
[解决办法]
因为cout是右先序的 。 
int add1(int a, int b)
{
std::cout<<"add1"<<std::endl;
return a+b;
}
int add2(int a, int b)
{
std::cout<<"add2"<<std::endl;
return a+b;
}

int main(int,char**)
{
std::cout << add1(1,2) << add2(1,2) << std::endl;
getchar();
return 0;
}

输出的是 
add2
add1
33
[解决办法]
1中的
cout<<*FuncTest(np,nM)<<endl<<*np<<endl;
此语句让*FuncTest(np,nM)和*np是同时执行的。虽然调用FuncTest函数让np指向了nM的地址,但是同时执行的np仍然指向nN的地址。
2中的
 cout<<*FuncTest(np,nM)<<endl;
cout<<*np<<endl; 
这两条语句是第一句先执行,然后执行第二句。而此时的np已经指向了nM的地址。
所以出现两种结果。

热点排行