#include<iostream>
#include<string>
template <typename T>
void swap(T a , T b)
{
T temp = a;
a = b;
b = temp;
}
template <typename T1>
void swap1(T1 a , T1 b)
{
T1 temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10 , b = 20;
std::string first = "hi" , last = "Bye";
swap(a,b);
swap(first, last);
std::cout<<"a = "<<a<<" b = "<<b<<std::endl;
std::cout<<"first = "<<first<<" last = "<<last<<std::endl;
int c = 50 , d = 100;
std::string name = "abc" , surname = "def";
swap1(c,d);
swap1(name,surname);
std::cout<<"c = "<<c<<" d = "<<d<<std::endl;
std::cout<<"name = "<<name<<" surname = "<<surname<<std::endl;
swap(c,d);
swap(name,surname);
std::cout<<"c = "<<c<<" d = "<<d<<std::endl;
std::cout<<"name = "<<name<<" surname = "<<surname<<std::endl;
return 0;
}
**Output**
a = 10 b = 20
first = Bye last = hi
c = 50 d = 100
name = abc surname = def
c = 50 d = 100
name = def surname = abc
两者swap()
和swap1()
基本上具有相同的函数定义,那么为什么swap()
实际上只交换字符串,而为什么swap1()
不交换?
还可以告诉我默认情况下如何将stl字符串作为参数传递,即它们是按值还是按引用传递?
4
有什么不对的std ::互换?
—
Jesper Juhl,
没错。我正在学习模板化功能。所以我写了这段代码只是为了练习,但是输出使我感到困惑。
—
GettingBetterprogrammer,