C++指针作为函数的参数进行传递时注意的问题

2014-11-23 22:08:40 ? 作者: ? 浏览: 3

应注意问题:
当指针作为函数的参数进行传递的时候,本质上还是进行的“值传递”,也就是复制了一个新的指向该地址的指针变量。

只有在被调函数中,对指针进行引用操作,才可以达到不需要返回值,就对指针指向的变量做出相应的变化。

下面分析这样两个例子;

要求:定义并初始化两个字符串变量,并执行输出操作;然后调用函数使这两个变量的值交换,并且要求被调函数的传值通过传递指针来实现。

程序1.1

[cpp]
#include
#include
using namespace std;
int main(){
string str1="I love China!",str2="I love JiNan!";
void Exchange(string *p1,string *p2);
cout<<"str1: "< cout<<"str2: "< Exchange(&str1,&str2);
cout<<"str1: "< cout<<"str2: "< return 0;
}
void Exchange(string *p1,string *p2){
string *p3;
p3=p1;
p1=p2;
p2=p3;
}

#include
#include
using namespace std;
int main(){
string str1="I love China!",str2="I love JiNan!";
void Exchange(string *p1,string *p2);
cout<<"str1: "< cout<<"str2: "< Exchange(&str1,&str2);
cout<<"str1: "< cout<<"str2: "< return 0;
}
void Exchange(string *p1,string *p2){
string *p3;
p3=p1;
p1=p2;
p2=p3;
}
输出结果:

\

程序1.2

[cpp]
#include
#include
using namespace std;
int main(){
string str1="I love China!",str2="I love JiNan!";
void Exchange(string *p1,string *p2);
cout<<"str1: "< cout<<"str2: "< Exchange(&str1,&str2);
cout<<"str1: "< cout<<"str2: "< cout< return 0;
}
void Exchange(string *p1,string *p2){
string p3;
p3=*p1;
*p1=*p2;
*p2=p3;
}

#include
#include
using namespace std;
int main(){
string str1="I love China!",str2="I love JiNan!";
void Exchange(string *p1,string *p2);
cout<<"str1: "< cout<<"str2: "< Exchange(&str1,&str2);
cout<<"str1: "< cout<<"str2: "< cout< return 0;
}
void Exchange(string *p1,string *p2){
string p3;
p3=*p1;
*p1=*p2;
*p2=p3;
}
输出结果:

\


分析:
通过这两个程序的结果对比,程序1.1中的函数没有达到交换数值的目的,而程序1.2达到了;

因为,在主函数中,主函数把str1和str2的首元素的地址,作为实参传递给了函数Exchange函数;Exchange函数中的,p1用于接收str1的地址,p2用于接收str2的地址,这个过程是进行了值传递。

在程序1.1中,只是指针p1和指针p2的值进行了交换,对原来的字符串str1和str2并没有什么影响;而在程序1.2中,是*p1和*p2的值进行了交换,而*p1就是str1它本身,*p2就是str2它本身,所以实际上是str1和str2进行了交换

-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: