提问人:Samvel Muqelyan 提问时间:10/4/2023 最后编辑:Remy LebeauSamvel Muqelyan 更新时间:10/5/2023 访问量:64
定义向量类复制构造函数时出现问题 (C++)
Problem in defining of Vector class Copy Constructor (C++)
问:
我试图手动定义一个类和它的一些函数。一切似乎都很好,直到我编写了复制构造函数,在循环的这一部分我收到了警告:Vector
this->arr[i] = vec.arr[i];
C6386:Buffer overrun while writing to 'this->arr'
#include <iostream>
using namespace std;
class Vector {
private:
int size, capacity;
int* arr;
public:
Vector(int _capacity = 5) : capacity(_capacity) {
size = 0;
arr = new int[capacity];
cout << "constructor" << endl;
}
~Vector() {
delete[] arr;
cout << "destructor" << endl;
}
Vector(const Vector& vec) {
this->capacity = vec.capacity;
this->size = vec.size;
this->arr = new int[this->capacity];
for (int i = 0; i < size; ++i) {
this->arr[i] = vec.arr[i]; //WARNING. C6386:Buffer overrun while writing to 'this->arr'
}
cout << "copy constructor" << endl;
}
void push_back(int n) {
if (size==capacity) {
resize();
}
arr[size] = n;
size++;
}
void resize() {
int* tmp = new int[capacity*=2];
for (int i = 0; i < size; ++i) {
tmp[i] = arr[i];
}
delete[] arr;
arr = tmp;
}
int Size() { return size; }
};
int main() {
Vector V1(3);
V1.push_back(1);
cout << V1.Size();
V1.push_back(4);
cout << V1.Size() << endl;
V1.push_back(4);
cout << V1.Size() << endl;
V1.push_back(4);
cout << V1.Size() << endl;
Vector V2(V1);
return 0;
}
我认为问题是我不够小心,我可能会让循环在某个地方出界,但似乎没关系。
你能帮我定义问题吗?
答: 暂无答案
评论