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

两个指针交换对象

2014-01-12 
两个指针互换对象我想用一个函数实现两个指针互换所指的对象,本人菜鸟,但是在函数中无法实现,于是在主函数

两个指针互换对象
我想用一个函数实现两个指针互换所指的对象,本人菜鸟,但是在函数中无法实现,于是在主函数中使用同一种方法,发现可以,想问一下这是为什么。谢谢各位大神解答。代码如下


#include<iostream>

using namespace std;
int main(){
int n1=12;
int n2=15;
int *p1=&n1;
int *p2=&n2;
int *temp;
cout<<"n1 is"<<n1<<"p1 is "<<*p1<<endl;
cout<<"n2 is"<<n2<<"p2 is "<<*p2<<endl;
//p1=p2;
//cout<<"n1 is"<<n1<<"p1 is "<<*p1<<endl;
//cout<<"n2 is"<<n2<<"p2 is "<<*p2<<endl;
//void ex_point(int *p1,int *p2);
//ex_point(p1,p2);
temp=p1;
p1=p2;
p2=temp;
cout<<"n1 is"<<n1<<"p1 is "<<*p1<<endl;
cout<<"n2 is"<<n2<<"p2 is "<<*p2<<endl;
return 0;
}

/*void ex_point(int *p1,int *p2){
int *temp;
temp=p1;
p1=p2;
p2=temp;
}*/

[解决办法]
函数形参用int **,也就是指针的指针,这样才会把传进来的实参指针的指向改变掉,其实跟交换两个实参的值是一样的道理,交换实参int的时候需要传入对象的地址,也就是int *,同样如果要交换两个指针的值,就需要传指针的地址,也就是int**了
[解决办法]
搜索下函数形参实参问题,
解决方案供参考:
void ex_point(int* &p1,int* &p2){ //指针的引用作为参数
int *temp;    
temp=p1;  
p1=p2;    
p2=temp;
}

[解决办法]
引用:

template <typename T>
void ex_point(T& p1, T& p2){
    T *temp;
    temp=p1;
    p1=p2;
    p2=temp;
}

那个模板有点写错了~


晕,还是写错了~

template <typename T>
void ex_point(T& p1, T& p2){
    T temp;
    temp=p1;
    p1=p2;
    p2=temp;
}

热点排行