using的使用

发布时间 2023-12-06 15:02:51作者: Beasts777

文章参考:

爱编程的大丙 (subingwen.cn)

1. C++98

在C++11之前,using有两种用法:

  • 用来声明要使用的命名空间:

    using namesapce std;
    
  • 当子类重载父类的同名成员函数时,通过using继承父类的同名函数。

    #include <iostream>
    using namespace std;
    
    class Person{
    public:
        void show(){
            cout << "Person" << endl;
        }
    };
    
    class Male: public Person{
    public:
        using Person::show;				// 继承基类中的show函数
        void show(int a){
            cout << "Male:" << a << endl;
        }
    }
    
    int main(void){
        Male m;
        m.show();				// 调用从基类中继承的show
        m.show(12);				// 调用自身实现的show
    	return 0;
    }
    

2. C++11

在C++11中,using有了一个新的用法:为类型起别名

这一点typedef也可以做到,但二者有一些不同的地方:

语法不同:

  • typedef

    typedef int my_int;
    my_int a = 10;
    
  • using

    using my_int = int;
    my_int a = 10;
    

显然,using的语法更加符合人们的习惯。通过为函数指针起别名,我们可以更加清楚的发现这一点:

  • typedef

    int add(int a, int b){
    	return a + b;
    }
    typedef int(func_ptr*)(int, int);
    func_ptr = add;
    func_pte(1, 2);
    
  • using

    int add(int a, int b){
    	return a + b;
    }
    using func_ptr = int(*)(int, int);
    func_ptr = add;
    func_pte(1, 2);
    

为模板起别名时不同:

  • typedef:typedef无法直接重新定义一个模板,需要为其添加一个外敷类

    #include <iostream>
    #include <map>
    using namespace std;
    
    template <typename T>
    typedef map<int, T> type;		// error,c++不支持这种语法。
    
    template <typename T>
    struct MyMap{
        typedef map<int, T> type;		// 通过添加外敷类,typedef可以为模板起别名。
    };
    MyMap<string>::type mm;
    mm.insert(make_pair(1, "zhangSan"));
    
  • using:可以直接重新定义一个模板:

    template <typename T>
    using map<int, T> type;		// 正确
    type<string> mm;
    mm.insert(make_pair(1, "zhangSan"));
    

综上:可以看出在重新定义某些类型时(起别名),using相较于typedef更加便利。