zoukankan      html  css  js  c++  java
  • 命名避免名字冲突

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

    程序如下:

    #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++命名规则,更要避免与系统重名,还要让别人容易读懂。

  • 相关阅读:
    终于清楚了!!!【使用jenkins发布应用到tomcat详细过程】
    RocketMQ相关问题
    关于idea修改当前使用的git账户的问题
    Elasticsearchan安装初尝01-问题记录
    Redis学习日记-03
    Git初探笔记02
    Git初探笔记01
    Redis学习日记-02
    HDU 1017
    HDU 1013
  • 原文地址:https://www.cnblogs.com/danshui/p/2452565.html
Copyright © 2011-2022 走看看