新微赢技术网

标题: [求助]这个std::bad_alloc错误怎么解决 [打印本页]

作者: 风声鹤唳    时间: 2009-11-3 01:28
标题: [求助]这个std::bad_alloc错误怎么解决
下面这个Matrix模板类,为什么运行时会有std::bad_alloc错误?
#ifndef MY_MATRIX_H
#define MY_MATRIX_H
#include "Vector.h"
template<class T>
class Matrix
{
public:
Matrix(unsigned r=1,unsigned c=1):row(r)
{ for(int i=0;i<r;i++) row[i]=new Vector<T>(c);} //std::bad_alloc?
~Matrix(){ for(int i=0;i<row.size();i++) delete [] row[i];}
Vector<T>& operator[](unsigned i) const { return *row[i];}
unsigned rows(){ return row.size();}
unsigned columns(){ return row[0]->size();}
protected:
Vector<Vector<T>*> row;
};
#endif
下面是其中用到的Vector.h
#ifndef MY_VECTOR_H
#define MY_VECTOR_H
template <class T>
class Vector
{
public:
Vector(unsigned n=8):_size(n),_data(new T[_size]){}
Vector(const Vector<T>& v):_size(v._size),_data(new T[_size]){copy(v);}
virtual ~Vector(){std::cout<<"Vector DESTRUCTION"<<std::endl;delete [] _data;}
Vector<T>& operator=(const Vector<T>&);
T& operator[](const unsigned i)const {return _data[i];}
unsigned size() const {return _size;}
protected:
T* _data;
unsigned _size;
void copy(const Vector<T>&);
};
template <class T>
Vector<T>& Vector<T>::operator=(const Vector<T>& v)
{
_size=v._size;
data=new T[_size];
copy(v);
return *this;
}
template <class T>
void Vector<T>::copy(const Vector<T>&)
{
unsigned min_size=(size<v._size?_size:v._size);
for(int i=0;i<min_size;i++)
data[i]=v._data[i];
}
#endif
编译时没有错误,但运行时,就有bad_alloc错误。
附件中的是上叙代码的文档。

附件: 只有本站会员才能下载或查看附件,请您 登录 或 注册
作者: 简单快乐    时间: 2009-11-3 01:28
下面的是测试代码

#include <iostream>
#include <cstdlib>
#include "Matrix.h"
int main()
{
Matrix<float> a(2,3);
a[0][0]=0.0; a[0][1]=0.1; a[0][2]=0.2;
a[1][0]=1.0; a[1][1]=1.1; a[1][2]=1.2;
std::cout<<"The matrix a has "<<a.rows()<<" rows and "
<<a.columns()<<" colums.\n";
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
std::cout<<a[i][j]<<" ";
std::cout<<std::endl;
}
system("pause");
return 0;
}




欢迎光临 新微赢技术网 (http://bbs.weiying.cn/) Powered by Discuz! X3.2