我正在做一个c++程序。这就是我必须做的:我创建一个我想要的大小的数组。该数组自动填充 0
。
使用运算符+= 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')|
提前谢谢您!
最佳答案
no match for
operator[]
(operand types are 'int [0]' and 'const bitArray')|
该错误非常清楚,operator[]
期望整数类型,而您传递的内容是 bitArray
类类型。简单的解决方法是将其更改为整数。
但是,这里:
private:
int sortie[];
int n;
强烈建议使用std::vector
,它提供连续的动态数组,而sortie[]
是静态分配。像这样的事情:
#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
,用可选的返回类型修改了上面的解决方案,这样应该更具可读性。
#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;
}
关于c++ - 用数组重载运算符 += C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50907657/