C++ : 类 类名::引用 { ... }

标签 c++ stl reference

我正在学习STL,从未见过像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
};
  • 这里的::引用有什么用?

我在这里看到了这段代码[在此处输入链接描述][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 Files\Microsoft Visual Studio 9.0\VC\include\bitset) 中,它们实际上是在彼此内部定义的:

// 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 相同,尽管稍微复杂一些。

关于C++ : 类 类名::引用 { ... },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7899256/

相关文章:

c++ - SSE2 - 16 字节对齐的内存动态分配

c++ - std::for_each 似乎正在清理 std::string

c++ - 关于初始化引用指针的问题

c++ - 什么时候将 node_type 与 std::map::insert 一起使用?

c++ - 你能初始化 unique_ptr 的 "static const vectors"吗? (C++17 与 GCC 7.3)

c - 如何使用指针替换字符串中的字符? (在 C 代码中)

c++ - 为什么双引用值在分配给 C++ 中的 float 变量时不会改变

c# - 通过 C++ dll 或 C++ exe 编写 C# GUI

c++ - 如何使用 WMI 更改 Win32_NetworkAdapter NetConnectionID 属性

c++ - Cython:如何移动大对象而不复制它们?