用于合并数组的重载运算符+失败
Overload operator+ for merging arrays fails
我试图理解复制和交换习惯用法,但当我使用operator+
(如Dumb_array c(a+b)
或a = a + b
(时,我的程序会崩溃。
#include "stdafx.h"
#include <iostream>
using std::cout; using std::endl;
class Dumb_array {
int* _array;
int _size;
public:
Dumb_array(size_t s)
: _size(s), _array(_size ? new int[s]() : nullptr) {
cout << "default constructor" << endl;
}
Dumb_array(const Dumb_array & other)
: _size(other._size), _array(_size ? new int[other._size]() : nullptr) {
cout << "copy constructor" << endl;
std::copy(other._array, other._array + sizeof(int) * _size, _array);
}
~Dumb_array() {
cout << "destructor" << endl;
delete[] _array;
}
Dumb_array& operator=(Dumb_array a) {
cout << "assigment" << endl;
swap(*this, a);
return *this;
}
Dumb_array operator+(Dumb_array& const other) const {
cout << "+" << endl;
int new_size = _size + other._size;
Dumb_array sum(new_size);
int i;
for (i = 0; i < _size; i++)
sum._array[i] = _array[i];
for (int j = 0; j < other._size; j++, i++)
sum._array[i] = other._array[j];
return sum;
}
friend void swap(Dumb_array& one, Dumb_array& another);
};
void swap(Dumb_array& one, Dumb_array& another) {
std::swap(one._size, another._size);
std::swap(one._array, another._array);
}
int _tmain(int argc, _TCHAR* argv[]) {
Dumb_array a(2);
Dumb_array b(a);
// Dumb_array c(a+b);
a = a + b;
std::system("pause");
return 0;
}
std::copy(other._array, other._array + sizeof(int)*_size, _array);
这个sizeof(int(不是必需的。您指向的是另一端之外的某个内存位置_大堆正确的线路是…
std::copy(other._array, other._array + _size, _array)
我希望这能解决你的问题。你应该弄清楚如何使用调试器,它对解决这些问题有很大帮助。
相关文章:
- 分配给转换运算符失败-C++
- 使用模板化运算符重载 XOR 运算符失败
- 为什么此对箭头 (->) 运算符的调用失败?
- ostream_iterator运算符=在pair<int,int>上失败,但在包装器类上工作。我不能为成对<>重载运算符<<吗?
- 调用以CWinThread为基的类运算符()的std::thread失败
- 为什么通过通用引用运算符 (&&) 将变量的引用传递给 Varadic 模板函数失败?
- 为什么在函数参数中使用赋值运算符会失败
- 字符串流运算符输入失败
- 如何修复此 OpenCV 错误:断言失败((无符号)i < (无符号)cn) 在 cv::Vec<unsigned char,3>:::运算符 (), 文件
- 为什么这C++检测T型是否具有空运算符(EDT const&)失败的特征?
- 运算符 == 重载函数失败
- 模板参数扣除失败因运算符重载而失败
- 打印运算符过载失败
- 具有重载<<运算符的简单模板类失败,"Invalid use of template-id"
- 是否保证标准提取运算符>>在失败时不会更改参数?
- 重载乘法运算符失败
- 如果 GCC 4.4.7 上未使用返回值,则强制调用类运算符 == 失败
- 运算符<<() 失败时回退到 to_string()
- 用于合并数组的重载运算符+失败
- 为什么我使用运算符*失败了?