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