我试图理解C ++中的引用和指针,但我偶然发现了这一点
#include<iostream>
using namespace std;
void swap(char * &str1, char * &str2)
{
char *temp = str1;
str1 = str2;
str2 = temp;
}
int main()
{
const char *str1 = "GEEKS";
const char *str2 = "FOR GEEKS";
swap(str1, str2);
cout<<"str1 is "<<str1<<endl;
cout<<"str2 is "<<str2<<endl;
return 0;
}
[交换]函数中的*&
是什么,与我所学的&
(通过引用传递)相比,性能上有什么不同,或者它们如何工作,我应该使用什么?
void swap(char &str1, char &str2)
{
char temp = str1;
str1 = str2;
str2 = temp;
}
是对指针的引用。这样,该函数不仅可以访问指针指向
可以在声明中引用任何类型。
将引用传递给指针非常类似于将引用传递给任何其他类型的变量。因此,在函数中: