注册 登录
编程论坛 C++教室

函数模板问题

小亦庄葛三娘 发布于 2017-03-21 14:08, 2028 次点击
程序代码:
template <typename  T>
void swap(T &a, T &b);

int main()
{
    int i = 10;
    int j = 20;
    cout << "i, j = " << i << ", " << j << ".\n";
    cout << "using complier generated int swapper:\n";
    swap(i, j);
    cout << "now i, j = " << i << ", " << j << ".\n";
   
    double x = 24.5;
    double y = 81.7;
    cout << "x, y = " << x << ", " << y << ".\n";
    cout << "using complier generated int swapper:\n";
    swap( x, y);
    cout << "now x, y = " << x << ", " << y << ".\n";
   
    return 0;
}

template <typename T>
void swap(T &a, T &b)
{
    T temp;
    temp = a;
    a = b;
    b = temp;
}


只有本站会员才能查看附件,请 登录



在学c++ primer plus里面的例题,但是编译不出来,求大神指教

[此贴子已经被作者于2017-3-21 14:10编辑过]

3 回复
#2
yuyu124092017-03-21 15:21
去掉:
template <typename  T>
void swap(T &a, T &b);这两行就可以了。
#3
yangfrancis2017-03-21 15:24
说是函数定义重复。换个函数名试试。
#4
rjsp2017-03-21 15:26
第一,代码要贴全,不是所有人都愿意花时间去补全代码。别人发现题主故意缺代码,就懒得回答了。
第二,错误信息说的是,你这个 swap 和 std::swap 暧昧了。
1