gpt4 book ai didi

c++ - 无效的对象访问 C++

转载 作者:行者123 更新时间:2023-11-28 00:16:13 25 4
gpt4 key购买 nike

我试图运行 Stroustroup 的 C++ 书中的这段代码,我添加了一些代码,因为书中没有所有内容。我一直遇到以下问题。我知道这里有多个关于同一个错误的问题,但我的代码不同,因此出现了这个问题。

错误是

copy(5826,0x7fff76b09300) malloc: * error for object 0x7ff6a9404c18: incorrect checksum for freed object - object was probably modified after being freed. * set a breakpoint in malloc_error_break to debug Abort trap: 6

#include<stdio.h>
#include<iostream>

using namespace std;
class Vector {
private:
double * elem; // elem points to an array of sz doubles
int sz;
public:
Vector(int s) {
sz = s;
elem = new double[sz];
for (int i = 0; i<sz; i++) {
elem[i] = i;
}
}
~Vector() { delete[] elem; } // destructor: release resources
Vector(const Vector& a); // copy constructor
Vector& operator=(const Vector& a); // copy assignment
double& operator[](int i);
const double& operator[](int i) const;
int size() const;
};


Vector::Vector(const Vector& a) // copy constr uctor
{
elem = new double[sz], // allocate space for elements
sz = a.sz;
for (int i = 0; i != sz; ++i) // copy elements
elem[i] = a.elem[i];
}


double& Vector::operator[](int k) {
return this->elem[k];
}


Vector& Vector::operator=(const Vector& a) // copy assignment
{
double* p = new double[a.sz];
for (int i = 0; i != a.sz; ++i)
p[i] = a.elem[i];
delete[] elem; // delete old elements
elem = p;
sz = a.sz;
return *this;
}


int main() {
Vector v1(10);
Vector v2 = v1;
v1[0] = 2;
v2[1] = 3;
cout << v1[0] << "\n";
return 0;
}

最佳答案

你的复制构造函数应该反转两行,因为你还没有为 sz 设置值。

Vector::Vector(const Vector& a) // copy constructor
{
elem = new double[sz];
sz = a.sz;
for (int i=0; i!=sz; ++i)
elem[i] = a.elem[i];
}

所以你可以这样做

Vector::Vector(const Vector& a) // copy constructor
{
sz = a.sz;
elem = new double[sz];
for (int i=0; i!=sz; ++i)
elem[i] = a.elem[i];
}

关于c++ - 无效的对象访问 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30170310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com