2011-10-26 57 views
2

我學習STL,從來沒有見過這樣的類也一樣class classname :: reference {}C++:類的類名::參考{...}

我在網上搜索,但能得到好的信息..

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 
}; 
  • 什麼是這裏的參考?

我在這裏看到這個代碼[此處輸入鏈接的描述] [1] http://www.cplusplus.com/reference/stl/bitset/ 我對前C++工作。

回答

2

你看了一下bitset類的定義嗎?有這樣的地方:

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

這就像把身體的功能可按類主體之外。現在,我們正在把一個嵌套類的身體的父類的外:

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

順便說一句,在MSVC(C:\Program Files\Microsoft Visual Studio 9.0\VC\include\bitset)the're實際上定義裏面對方:

// 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也是如此,雖然有點複雜。

1

引用是類名,沒什麼特別的。 bitset :: reference表示引用是內部類。

1

你引用的段之前的行權解釋說:

因爲沒有這樣的小元素類型在大多數C++環境中存在,個體元素作爲模仿布爾元素的特殊引用訪問

C++不允許引用位域,因此使用reference類來模擬它。

1

這是一個nested class。從文章:

一個類可以在另一個類的範圍內聲明。這樣的一個類被稱爲「嵌套類」。嵌套類在封閉類的範圍內被認爲是 ,並且在該範圍內可以使用 。要引用其直接封閉範圍以外的作用域的嵌套類,必須使用完全限定名稱。

另一種解釋是,bitset類不僅用作類而且用作命名空間。