本文介绍了如果我将函数命名为`swap`,为什么会出现模板错误,但是`Swap`可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这样程序就可以正常运行

Alright so heres the program and works absolutely right

#include <iostream>

using namespace std;

template <typename T>
void Swap(T &a , T &b);

int main(){

    int i = 10;
    int j = 20;

    cout<<"i, j = " << i <<" , " <<j<<endl;
    Swap(i,j);
    cout<<"i, j = " << i <<" , " <<j<<endl;


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

但是当我将函数的名称从 交换 更改为 交换 时它会显示一条错误消息

but when I change the function's name from Swap to swapit generates an error saying

使用模板以大写字母开头的函数启动规则是怎么回事?

what happened is it a rule to start functions using templates to start with a capital letter ?

推荐答案

这是因为已经存在一个名为 swap 的函数.它实际上位于 std 命名空间下,但是由于您具有 using namespace std 行,因此它存在时没有 std :: 前缀.

This is because there already exists a function called swap. It is actually under the std namespace, but because you have a using namespace std line, it exists without the std:: prefix.

如您所见,如本例所示,由于可能发生名称冲突,因此使用 using命名空间std 并非总是一个好的选择.通常,除非有真正的原因(名称空间存在是有原因的)以防止名称冲突,否则通常不应该使用 using 指令.

As you can see, using the using namespace std isn't always a good option because of possible name collisions, as in this example. In general one should prefer not to use the using directive unless there's a real reason for this - namespaces exist for a reason - to prevent name collisions.

这篇关于如果我将函数命名为`swap`,为什么会出现模板错误,但是`Swap`可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 16:24