#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
template<class T>
void mySwap(T& a, T& b)
{
T temp = a;
a = b;
b = temp;
}
void test1(){
int a=1,b=2;
// mySwap(a,b);
mySwap(1,2);//报错哦############################
cout<<a<<" "<<b<<endl;
float c=1.1,d=2.2;
mySwap<float>(c,d);
cout<<c<<" "<<d<<endl;
}
int main(int argc, char** argv) {
test1();
return 0;
}
C:\Users\Administrator\Desktop\C++\main.cpp [Error] invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'
模板这里不能直接用常量,用变量。改成上面一行的内容就不报错了~
博客探讨了C++编程中模板的使用,特别是在`mySwap`模板函数的应用上。指出直接使用常量作为参数会导致编译错误,而传入变量则能正确运行。文章通过示例展示了如何正确调用模板函数,强调了模板参数必须为可修改的引用类型。
3万+

被折叠的 条评论
为什么被折叠?



