命名避免名字冲突

今天在写了模板函数时出现下面情况:

程序如下:

#include <iostream>
#include <string>
using namespace std;

template <class T> 
void swap(T &a,T &b)//swap already exist in STL
{
    T temp(a);
    a=b;
    b=temp;
}

int main()
{
    string a("hello"),b("world");
    //int a=1,b=2;
    swap(a,b);
    cout<<"a= "<<a<<"\t"<<"b= "<<b<<endl;

    return 0;
}

编译竟然报错:

error C2667: 'swap' : none of 2 overload have a best conversion

error C2668: 'swap' : ambiguous call to overloaded function Error executing cl.exe.

overload?重载?我想我只写了一个函数怎么会重载呢?

后面才发现:我虽然只写了一个函数,但STL已经写好swap函数了,所以当然会出现重载了,所以只需要将swap改为my_swap即可。

正确代码如下:

#include <iostream>
#include <string>
using namespace std;

template <class T> 
void my_swap(T &a,T &b)//swap already exist in STL
{
    T temp(a);
    a=b;
    b=temp;
}

int main()
{
    string a("hello"),b("world");
    //int a=1,b=2;
    my_swap(a,b);
    cout<<"a= "<<a<<"\t"<<"b= "<<b<<endl;

    return 0;
}

运行结果:

a= world        b= hello

 

后记:命名有时候不仅是牵涉到是否符合C++命名规则,更要避免与系统重名,还要让别人容易读懂。

原文地址:https://www.cnblogs.com/danshui/p/2452565.html