zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

C++ 问题 函数 进行 参数 需要 一些 注意
2023-06-13 09:15:06 时间

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

下面分析这样两个例子;

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

程序1.1
复制代码代码如下:

#include<iostream>
#include<string>
usingnamespacestd;
intmain(){
  stringstr1="IloveChina!",str2="IloveJiNan!";
  voidExchange(string*p1,string*p2);
  cout<<"str1:"<<str1<<endl;
  cout<<"str2:"<<str2<<endl;
  Exchange(&str1,&str2);
  cout<<"str1:"<<str1<<endl;
  cout<<"str2:"<<str2<<endl;
  return0;
}
voidExchange(string*p1,string*p2){
 string*p3;
 p3=p1;
 p1=p2;
 p2=p3;
}

输出结果:


程序1.2
复制代码代码如下:

#include<iostream>
#include<string>
usingnamespacestd;
intmain(){
  stringstr1="IloveChina!",str2="IloveJiNan!";
  voidExchange(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;
  return0;
}
voidExchange(string*p1,string*p2){
 stringp3;
 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进行了交换