我試圖從Stroustroup的C++書籍中運行此代碼,我添加了一些代碼,因爲書中沒有提供任何東西。我一直在觸及以下問題。我知道在這裏有同樣的錯誤有多個問題,但我的代碼是不同的,因此這個問題。無效的對象訪問C++
的錯誤是
副本(5826,0x7fff76b09300)的malloc:*錯誤對象0x7ff6a9404c18:用於釋放對象不正確的校驗 - 對象被釋放後,可能被修改。 *設置斷點malloc_error_break調試 中止陷阱: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;
}
謝謝,這一個擺脫了我的注意,它很難找到這個與我得到的錯誤信息,爲什麼系統會拋出這個錯誤? –