源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2022-07-15 01:18 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C++指针作为函数的参数进行传递时需要注意的一些问题
只有在被调函数中,对指针进行引用操作,才可以达到不需要返回值,就对指针指向的变量做出相应的变化。 [b]下面分析这样两个例子;[/b] 要求:定义并初始化两个字符串变量,并执行输出操作;然后调用函数使这两个变量的值交换,并且要求被调函数的传值通过传递指针来实现。 程序1.1
[u]复制代码[/u] 代码如下:
#include<iostream> #include<string> using namespace std; int main(){    string str1="I love China!",str2="I love JiNan!";    void Exchange(string *p1,string *p2);    cout<<"str1: "<<str1<<endl;    cout<<"str2: "<<str2<<endl;    Exchange(&str1,&str2);    cout<<"str1: "<<str1<<endl;    cout<<"str2: "<<str2<<endl;    return 0; } void Exchange(string *p1,string *p2){  string *p3;  p3=p1;  p1=p2;  p2=p3; }
输出结果: [img]http://files.jb51.net/file_images/article/201310/2013101610295023.jpg[/img] 程序1.2
[u]复制代码[/u] 代码如下:
#include<iostream> #include<string> using namespace std; int main(){    string str1="I love China!",str2="I love JiNan!";    void Exchange(string *p1,string *p2);    cout<<"str1: "<<str1<<endl;    cout<<"str2: "<<str2<<endl;    Exchange(&str1,&str2);    cout<<"str1: "<<str1<<endl;    cout<<"str2: "<<str2<<endl;    cout<<endl;    return 0; } void Exchange(string *p1,string *p2){  string p3;  p3=*p1;  *p1=*p2;  *p2=p3; }
输出结果: [img]http://files.jb51.net/file_images/article/201310/2013101610295024.jpg[/img] 分析: 通过这两个程序的结果对比,程序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进行了交换
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部