【问题标题】:C++ - What does reference& operator= do hereC++ - reference& operator= 在这里做什么
【发布时间】:2014-06-27 03:43:09
【问题描述】:

我在阅读有关 C++11 STL 中向量的一些内容时遇到了这段代码。它使用 operator= 的赋值。现在我无法弄清楚它到底做了什么。

代码如下:

namespace std {

    template <typename Allocator> class vector<bool, Allocator> {
    public:
        // auxiliary proxy type for element modifications:

        class reference {
            ...
        public:
            reference& operator=(const bool ) noexcept; // assignments
            reference& operator=(const reference&) noexcept;
            operator bool( ) const noexcept; // automatic type conversion to bool
            void flip( ) noexcept;
            // bit complement
        };
        ...
        // operations for element access return reference proxy instead of bool:
        reference operator[]( size_type idx );
        reference at( size_type idx );
        reference front( );
        reference back( );

    };
}

从上面的代码我可以理解它返回一个类引用类型。但我无法理解的是这个声明reference&amp; operator=(const reference&amp;) noexcept;。 请让我知道这句话在这种情况下的实际含义是什么

【问题讨论】:

标签: c++ c++11


【解决方案1】:

reference 类是所谓的代理,它伪装成另一种类型来赋予它你无法获得的行为。在这种情况下,它代替了bool,因此它需要分配给bool。可以看到这个类上有两个operator=方法,一个取bool,一个取reference&amp;

operator= 的规则之一是它必须返回对对象的引用,以便您可以链接 = 运算符:

b1 = b2 = false;

【讨论】:

  • 解释得很清楚。非常感谢。现在我了解了它的应用。它可以称为一种多态性吗?因为代理类可以充当多种类型。
  • @Maxx 我不认为多态性是描述它的正确方式,但我无法用语言表达我为什么这么认为。
【解决方案2】:

使用reference 作为一个类是一个糟糕的选择。但是……

功能

reference& operator=(const bool ) noexcept;

返回对reference 类型对象的引用。最有可能的是,函数中的 return 语句如下所示:

return *this;

上一堂简单的课:

struct A
{
   A(int in) : data(in) {}
   A& operator=(int in)
   {
      data = in;
      return *this;
   }

   A& operator=(A const& rhs)
   {
      data = rhs.data;
      return *this;
   }
};

用法:

A a(10); // a.data is 10
a = 20;  // a.data is 20
A b(5);  // b.data is 5
a = b = 35; // a.data as well as b.data are 35

【讨论】:

    【解决方案3】:

    你说得对,它返回一个reference 对象(实际上它返回一个对reference 对象的引用——这就是&amp; 的意思)。

    方法名称表明您正在重载赋值运算符=

    该方法的参数意味着它采用对reference 对象的不可变(const 关键字)引用。

    noexcept 关键字承诺该方法不会抛出异常。如果你违背了这个承诺,你的程序将抛出一个运行时异常。

    C++ 程序员会将其解释为复制赋值运算符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-28
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多