C++ : class classname :: reference { ... }

C++ : class classname :: reference { ... }

本文关键字:reference classname class C++      更新时间:2023-10-16

我还在学习,从来没有见过像class classname :: reference {}这样的课

我在网上搜索,但可以得到很好的信息。

class bitset::reference {
  friend class bitset;
  reference();                                 // no public constructor
public:
  ~reference();
  operator bool () const;                      // convert to bool
  reference& operator= ( bool x );             // assign from bool
  reference& operator= ( const reference& x ); // assign from bit
  reference& flip();                           // flip bit value
  bool operator~() const;                      // return inverse value
};

    i see this code here[enter link description here][1]http://www.cplusplus.com/reference/stl/bitset/我以前做过c++

    你看bitset类的定义了吗?在某个地方有这样的内容:

    template<size_t _Bits>
    class bitset
    {
        ...
        class reference;
        ...
    }
    

    这很像把函数体放在类体之外。现在我们将嵌套类的主体放在父类的外部:

    class bitset::reference
    {
        /* class body */
    }
    

    顺便说一下,在MSVC (C:Program FilesMicrosoft Visual Studio 9.0VCincludebitset)中,它们实际上是在彼此内部定义的:

    // TEMPLATE CLASS bitset
    template<size_t _Bits>
    class bitset
    {   // store fixed-length sequence of Boolean elements
    typedef unsigned long _Ty;  // base type for a storage word
    enum {digits = _Bits};  // extension: compile-time size()
    public:
    typedef bool element_type;  // retained
        // CLASS reference
    class reference
        {   // proxy for an element
        friend class bitset<_Bits>;
        .
        .
        .
    

    对于g++的bitset.h也是一样的,尽管稍微复杂一些。

    引用是类名,没有什么特别的。Bitset::reference表示引用是内部类

    你引用的代码片段前一行解释:

    因为在大多数c++环境中不存在这样的小元素类型,所以单个元素被作为模拟bool元素的特殊引用来访问

    c++不允许引用位域,所以用reference类来模拟。

    这是一个嵌套类。摘自文章:

    一个类可以在另一个类的作用域中声明。这样一个类称为"嵌套类"。嵌套类被认为是在封闭类的作用域内,并且可供使用在这个范围内。从作用域以外的范围引用嵌套类对于它的直接封闭作用域,必须使用完全限定名。

    另一种解释是,bitset类不仅被用作类,而且还被用作名称空间。