【问题标题】:How to control value assigned by operator []如何控制运算符 [] 分配的值
【发布时间】:2017-08-21 09:23:08
【问题描述】:

我知道如何重载operator[] 如下:

T& operator [](int idx) {
    return TheArray[idx];
}

T operator [](int idx) const {
    return TheArray[idx];
}

但我想要控制arr[i] = value 分配的值。 我想将值控制在 0 到 9 之间。 有什么语法可以这样做吗?

【问题讨论】:

  • 你需要返回一个包装元素的代理对象,并让它对赋值进行范围检查。
  • 控制是什么意思?是要触发编译错误,还是要在运行时抛出异常,还是要静默忽略赋值,还是要截断不在范围内的值?
  • @taskinoor 正如我们对类的一贯做法......我们想抛出异常!
  • 澄清问题。你想对operator[] 的结果进行范围检查,还是要存储一个范围检查的T?在我看来,在容器之外有一个可以有任何值的对象似乎很奇怪,但容器内的对象有一个有限的范围。 (如果插入一个已经越界的对象会怎样?)
  • 应该很奇怪 :))) 我正在做一个 BigNum 项目,我已经将每个数字存储在一个整数向量中。你是对的......对于一种方法,我可以定义一个名为 digit 的类并将边界应用于该类。

标签: c++ operator-overloading operator-keyword


【解决方案1】:

您必须编写一个模板类,该类包含对数组(类型 T)中元素的引用,在此模板中您实现赋值运算符,并在那里您可以实现您的检查。然后从 [] 运算符返回此模板类的对象。

类似这样的:

template< typename T> class RangeCheck
{
public:
   RangeCheck( T& dest): mDestVar( dest) { }
   RangeCheck& operator =( const T& new_value) {
      if ((0 <= new_value) && (new_value < 9)) {  // <= ??
         mDestVar = new_value;
      } else {
         ... // error handling
      }
      return *this;
   }
private:
   T&  mDestVar;
};

【讨论】:

    【解决方案2】:

    Rene 提供了一个很好的答案。除此之外,这里有一个完整的例子。请注意,我在proxy_T 类中添加了“用户定义的转换”,即operator T

    #include <iostream>
    #include <array>
    #include <stdexcept>
    
    template <class T>
    class myClass
    {
        std::array<T, 5> TheArray; // Some array...
    
        class proxy_T
        {
            T& value; // Reference to the element to be modified
    
        public:
            proxy_T(T& v) : value(v) {}
    
            proxy_T& operator=(T const& i)
            {
                if (i >= 0 and i <= 9)
                {
                    value = i;
                }
                else
                {
                    throw std::range_error(std::to_string(i));
                }
                return *this;
            }
    
            operator T() // This is required for getting a T value from a proxy_T, which make the cout-lines work
            {
                return value;
            }
        };
    
    public:
        proxy_T operator [](int const idx)
        {
            return TheArray.at(idx);
        }
    
        T operator [](int const idx) const
        {
            return TheArray[idx];
        }
    };
    
    int main() {
        myClass<int> A;
    
        std::cout << A[0] << std::endl;
        A[0] = 2;
        std::cout << A[0] << std::endl;
        A[1] = 20;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      相关资源
      最近更新 更多