2011-10-26 59 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类不仅用作类而且用作命名空间。