一般来说,函数出参采用指针形式和引用形式。
注:&多用于参数传入,对于传出参数还是用*的比较好。用*可以设计缺省值,而&确不能。
#include <iostream>
using namespace std;
void SwapByPoint(int* x, int* y) //指针传参函数的声明
{
*x = *y = 1;
}
void SwapByReference(int &x, int &y) //引用传参函数的声明
{
x = y = 2;
}
int main()
{
int x = 3;
int y = 5;
cout << "转化前: x=" << x << " y=" << y << "\n";
SwapByPoint(&x, &y); //如果这里使用 SwapByPoint(x,y) 则报错:cannot convert parameter 1 from 'int' to 'int *'
cout << "指针传参转换后:x=" << x << " y=" << y << "\n";
SwapByReference(x, y); //如果这里用SwapByReference(&x,&y) 则报错 cannot convert parameter 1 from 'int *' to 'int &'
cout << "引用传参调用转换后:x=" << x << " y=" << y << "\n";
system("pause");
return 0;
}
#include<iostream>
using namespace std;
void test1(char* str)
{
str = "guoke";
}
void test2(char** str)
{
*str = "guoke";
}
int main()
{
char *s = "abc";
test1(s);
cout << "test1: " << s << endl; // 输出 abc
test2(&s);
cout << "test2: " << s << endl; // 输出guoke
system("pause");
return 0;
}