0
我想實現一個容器將內存分配給堆,但它好像我的基構造函數和我的參數構造函數不喜歡彼此。下面,我發佈了沒有任何註釋的代碼。就目前而言,它崩潰了。在複製構造函數和賦值運算符中刪除私有數組
#include <iostream>
using namespace std;
class foo
{
public:
foo() {size=1; vals = new double[1]; vals[0]=0;}
~foo() {delete[] vals;}
foo(const foo& other)
{
size=other.getsize();
delete[] vals;
vals = new double[size];
for(long unsigned i=0; i<size; i++)
vals[i]=other[i];
}
foo& operator=(const foo& other)
{
size=other.getsize();
delete[] vals;
vals = new double[size];
for(long unsigned i=0; i<size; i++)
vals[i]=other[i];
return *this;
}
foo(double* invals, long unsigned insize)
{
size=insize;
delete[] vals;
vals = new double[size];
for(long unsigned i=0; i<size; i++)
vals[i]=invals[i];
}
double operator[](long unsigned i) const {return vals[i];}
long unsigned getsize() const {return size;}
private:
double* vals;
long unsigned size;
};
int main()
{
double bar[3] = {5,2,8};
foo B(bar, 3);
cout<< B[0]<< " "<< B[1]<< " "<< B[2]<<endl; //couts fine
foo A; //crashes here
return 0;
}
但是,當我改變主要是:
int main()
{
double bar[3] = {5,2,8};
foo B(bar, 3);
cout<< B[0]<< " "<< B[1]<< " "<< B[2]<<endl; //couts fine
foo A(); //works now
return 0;
}
運行良好。但是,我不能指定A = B,因爲它認爲foo是一個函數或其他東西。
如果你想在當時沒有任何東西的時候使用'delete',你必須根據你的需要重載刪除操作符,因爲當那個對象被調用的時候,這個對象中什麼也沒有,這可能是問題爲你的崩潰.. – goodies