简体   繁体   English

用数组C ++重载运算符+ =

[英]Overloading operator += with array c++

I am doing a c++ program. 我正在做一个c ++程序。 Here's what I have to do: I create an array of the size I want. 这是我必须要做的:创建所需大小的数组。 The array is auto-filled with 0 . 数组自动填充为0

With the operator += i have to insert 1 at the place i chose. 对于operator += i必须在i选择的位置插入1 Example : 范例:

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

But how can I do it ? 但是我该怎么办呢?

My .h file 我的.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

My method in the cpp file : 我在cpp文件中的方法:

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

But it does not work. 但这行不通。 Am I doing the right way? 我做对了吗?

My error is : 我的错误是:

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

Thank you in advance ! 先感谢您 !

no match for operator[] (operand types are 'int [0]' and 'const bitArray')| operator[]不匹配(操作数类型为“ int [0]”和“ const bitArray”)|

The error is crystal clear that the operator[] expecting an interger type and what you passing a bitArray class type. 该错误非常明显,即operator[]期望使用整数类型,以及您传递的bitArray类类型是什么。 Simple fix is to change it to integer. 简单的解决方法是将其更改为整数。

However, here: 但是,这里:

private:
    int sortie[];
    int n;

it is highly recommended to use std::vector , which gives a contiguous dynamic array whereas sortie[] is static allocation. 强烈建议使用std::vector ,它提供连续的动态数组,而sortie[]是静态分配。 Something like this: 像这样:

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;
}

Update : Using C++17 feature std::optional , modified the above solution with the optional return type, which should be more readable. 更新 :使用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;
}

Your operator+= takes a bitArray as parameter, but it should take the index where to set the 1 and thats basically what the error message is trying to tell you: There is no overload for the parameters you are trying to use it. 您的operator+=bitArray作为参数,但应该将设置1的索引作为索引,这基本上就是错误消息试图告诉您的内容:您尝试使用它的参数没有重载。

Note that to get such an operator you dont need to write your own array class, but you can provide an overload for std::vector : 请注意,要获得这样的运算符,您无需编写自己的数组类,但可以为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;
}

Note that this is a rather uncommon way to implement += (it does not really add anything). 请注意,这是实现+=一种非常不常见的方式(它实际上并没有添加任何内容)。 I would consider this as misuse of operator overloading and it will lead to obfuscated code. 我认为这是滥用运算符重载,并且会导致代码混淆。 Consider this: 考虑一下:

vec[5] = 1;

vs VS

vec += 5;

In the first line, everybody who is familiar with std::vector will know what it does, while for the second line 90% of the expectations will be off. 在第一行中,每个熟悉std::vector都将知道它的作用,而在第二行中,90%的期望值将消失。 I guess you are doing this as part of an assignment or homework, though for anything else I would suggest you to stay away from using operator overloads that do anything more than the obvious thing. 我想您是作为作业或家庭作业的一部分来执行此操作的,尽管对于其他任何事情,我建议您不要使用运算符重载,而该操作符要做的事情不外乎显而易见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM