C++ 中using 的使用


C++ 中using 的使用

#include <iostream>

using namespace std;

class ClassOne 
{
public:
    int w;
protected:
    int a;
};

class ClassTwo
{
public:
    using ModuleType = ClassOne;
};

template <typename ClassType>class ClassThree : private ClassType
{
public:
    using typename ClassType::ModuleType;
    ModuleType m;
    ClassThree() = default;
    virtual ~ClassThree() = default;
};

void main()
{
    ClassThree<ClassTwo>::ModuleType a;
}

 

在上面代碼中,一共有三處使用了using,分別是第3,16,22行,它們的作用為:

  • 引入命名空間
  • 指定別名
  • 在子類中引用基類的成員

引入命名空間

指定命名空間是C++ using namespace中最常被用到的地方,在第3行中的:

 using namespace std; 

指定別名

using的另一個作用是指定別名,一般都是using a = b;這樣的形式出現,比如在13行中:

 using ModuleType = ClassOne; 

ModuleType 是ClassOne的一個別名。
using這個作用也比較常見,比如在vector.h中就有:

template<class _Ty,class _Alloc = allocator<_Ty>>class vector: public _Vector_alloc<_Vec_base_types<_Ty, _Alloc>>
{
public:
    using value_type = _Ty;
    using allocator_type = _Alloc;
}

 

value_type 是_Ty的一個別名, value_type a;  和 _Ty a; 是同樣的效果。

在子類中引用基類的成員

using的第三個作用是子類中引用基類的成員,一般都是using CBase::a;這樣的形式出現,比如在22行中:

 using typename ClassType::ModuleType; 

它和一般形式有些區別,就是它加了個typename 修飾,這是因為類ClassThree本身是個模板類,它的基類ClassType是個模板,這個typename 和using其實沒有什么關系。如果ClassType不是模板的話,這行代碼就可以寫成:

 using ClassType::ModuleType; 

剩下的就是using的作用,它引用了基類中的成員ModuleType, ModuleType又是類ClassOne的別名,所以后面ModuleType m;相當於定義對象m,對於子類成員m來說,這樣的效果和下面是相同的:

 typename ClassType::ModuleType m; 

不同之處在於using還修改了基類成員的訪問權限,子類ClassThree 私有繼承ClassType,所以ClassType中共有成員ModuleType 在子類ClassThree 是私有的,它不能被外部訪問。但是使用using后,在main()函數中可以使用。

 

參考鏈接:https://blog.csdn.net/chaipp0607/article/details/100128842

     https://blog.csdn.net/jingerppp/article/details/78742459


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM