#include
using namespace std;
template <typename type1>
type1 ave(type1 a, type1 b)
{
a = b;
cout << "函数模板";
return 0;
}
int main()
{
int a = 0;
int b = 1;
int& la = a;
int& lb = b;
int c = ave(la, lb);
cout << c<<" " << a << " " << b;
system("pause");
return 0;
}
这里传了引用进去,为什么没有改变a和b的值
该回答引用ChatGPT
在你的代码中,虽然你在 main() 函数中使用了引用来初始化 la 和 lb,但是在调用 ave() 函数时,你传递了 la 和 lb 的值而不是它们的引用。这意味着在 ave() 函数中对参数 a 和 b 的更改不会反映到 main() 函数中的变量 a 和 b 上。
如果你想通过引用来传递参数,你可以将函数模板的参数类型改为引用类型,如下所示:
template <typename type1>
type1 ave(type1& a, type1& b)
{
a = b;
cout << "函数模板";
return 0;
}
这样,在 main() 函数中传递 la 和 lb 就会通过引用传递, ave() 函数中的更改会反映到 main() 函数中的变量 a 和 b 上,如下所示:
int a = 0;
int b = 1;
int& la = a;
int& lb = b;
int c = ave(la, lb);
cout << c << " " << a << " " << b;
输出将是 0 1 1,因为 a 和 b 都被设置为 1,并且 c 被设置为 0,这是 ave() 函数的返回值。
函数按下面方法定义试试
type1 ave(type1 &a, type1 &b)