【问题标题】:Overloading operator += with array c++用数组 C++ 重载运算符 +=
【发布时间】:2018-11-27 04:37:39
【问题描述】:

我正在做一个 c++ 程序。这就是我要做的:我创建一个我想要的大小的数组。数组自动填充0

使用operator += i 必须在i 选择的位置插入1。 示例:

array += 2; 
will insert 1 at the index 2 of my array.

但是我该怎么做呢?

我的 .h 文件

#ifndef BITARRAY_H
#define BITARRAY_H
#include <ostream>

class bitArray
{
public:
    bitArray(int n);
    virtual ~bitArray();

    bitArray& operator+=(const bitArray&); //this operator
    bitArray& operator-=(const bitArray&);
    int& operator[] (int x) {
      return sortie[x];
  }
protected:
private:
    int sortie[];
    int n;
};

//ostream& operator<<(ostream&, const bitArray&);
#endif // BITARRAY_H

我在cpp文件中的方法:

bitArray& bitArray::operator+=(const bitArray& i)
{
    this ->sortie[i] = 1;
    return *this;
}

但它不起作用。我做对了吗?

我的错误是:

no match for 'operator[]' (operand types are 'int [0]' and 'const bitArray')|

提前谢谢你!

【问题讨论】:

  • 参数应该是一个int。
  • @rustyx 或size_t。顺便说一下,您的数组 sortie 似乎需要动态分配,因为 n 是一个运行时参数。

标签: c++ arrays class c++11 operator-overloading


【解决方案1】:

operator[] 不匹配(操作数类型为 'int [0]' 和 'const 位数组')|

错误很清楚,operator[] 期望一个整数类型,而你传递了一个 bitArray 类类型。简单的解决方法是将其更改为整数。

但是,这里:

private:
    int sortie[];
    int n;

强烈推荐使用std::vector,它给出一个连续的动态数组,而sortie[]是静态分配。像这样的:

See live here

#include <iostream>
#include <vector>
#include <cstddef>

class bitArray
{
private:
   std::vector<int> sortie;
public:
   explicit bitArray(int size): sortie(size) {}
   bitArray& operator+=(const std::size_t i)
   {
      if (0 <= i && i < sortie.size()) // check for (0 <= index < size) of the array
      {
            this ->sortie[i] = 1;
            return *this;
      }
      else
      {
         // do your logic! for instance, I have done something like follows:
         std::cout << "out of bound" << std::endl;
         if(sortie.size() == 0) sortie.resize(1,0); // if the size of array == 0            
      }
      return *this;
   }
   int operator[] (const std::size_t index)
   {
      return (0 <= index && index < sortie.size()) ? sortie[index] : -1;
   }
};
int main ()
{
   bitArray obj(3);
   obj += 0;  std::cout << obj[0] << std::endl;
   obj += -2; std::cout << obj[-2] << std::endl;
   obj += 22; std::cout << obj[22] << std::endl; 
   return 0;
}

更新:使用 C++17 特性std::optional,将上述解决方案修改为可选返回类型,应该更具可读性。

See output in wandbox

#include <iostream>
#include <vector>
#include <cstddef>
#include <optional>

class bitArray
{
private:
   std::vector<int> sortie;
public:
   explicit bitArray(int size): sortie(size) {}
   // optional is used as the return type
   std::optional<bitArray> operator+=(const std::size_t i)
   {
      if (i < sortie.size()) // check for (0 <= index < size) of the array
      {
            this -> sortie[i] = 1;
            return std::optional<bitArray>{*this};
      }
      std::cout << "out of bound operation+= \t";
      return std::nullopt;    // std::nullopt to create any (empty) std::optional
   }
   std::optional<int> operator[] (const std::size_t index)
   {
      if(index < sortie.size())   return std::optional<int>{sortie[index]};
      else
      {
         std::cout << "out of bound operator[]: ";
         return std::nullopt;
      }
   }
};
int main ()
{
   bitArray obj(3);
   obj += 0;  std::cout << obj[0].value_or(-1) << std::endl;
   obj += -2; std::cout << obj[-2].value_or(-1) << std::endl;
   bitArray obj1(0);
   obj1 += 22; std::cout << obj1[22].value_or(-1) << std::endl;
   return 0;
}

【讨论】:

  • 如果您要检查越界并传递一个 int,您可能也应该检查该值是否至少为 0。
  • @Qubit:你的意思是:if (i &lt; n &amp;&amp; i &gt; 0)?
  • ...或者传递一个size_t,它比int更自然地用于索引
  • 为什么要通过 const 引用传递 i?这不是一个好习惯,请参阅,例如,Passing integers as constant references versus copying
  • 如果使用向量,n 是多余的
【解决方案2】:

您的operator+= 采用bitArray 作为参数,但它应该采用设置1 的索引,这基本上就是错误消息试图告诉您的内容:您的参数没有过载尝试使用它。

请注意,要获得这样的运算符,您不需要编写自己的数组类,但可以为std::vector 提供重载:

#include <iostream>
#include <vector>

template <typename T> 
std::vector<T>& operator+=(std::vector<T>& v,size_t index) {
    v[index] = 1;
    return v;
}     

int main() {
    auto vec = std::vector<int>(10,0);
    vec += 5;
    std::cout << vec[5];
    return 0;
}

请注意,这是实现+= 的一种相当不常见的方式(它实际上并没有添加任何东西)。我认为这是对运算符重载的滥用,它会导致代码混淆。考虑一下:

vec[5] = 1;

对比

vec += 5;

在第一行中,熟悉std::vector 的每个人都会知道它的作用,而对于第二行,90% 的期望将被取消。我猜你这样做是作为作业或家庭作业的一部分,但对于其他任何事情,我建议你不要使用操作符重载,因为它们做的事情不仅仅是显而易见的事情。

【讨论】:

  • @David 考虑接受其中一个答案。我实际上会投票给另一个,因为它更直接地解决了您的问题
  • @user463035818 实现+=的不常见方式这是一个很好的观点,我错过了。 +1
  • @JeJo 当我刚接触 C++ 时,我喜欢这样一个事实,即你可以让操作员做任何你想做的事情。但是,我变得更加保守,如果操作员的工作不是非常清楚和明显,我总是更喜欢具有描述性名称的方法
猜你喜欢
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-19
  • 1970-01-01
相关资源
最近更新 更多