template <class ElementType,int Dimension=1>
class Vector : public vector<ElementType> {
public:
Vector & operator+= (const Vector & a){
cout << " a " << a << endl;
transform (this->begin(), this->end(), a.begin(), this->begin(), plus<ElementType>());
return *this;
};
friend ostream & operator<< (ostream & stream, Vector t) {
stream << "(";
copy (t.begin(), t.end()-1, ostream_iterator<ElementType>(stream,","));
return stream << *(t.end()-1) << ")";
};
};
1)在運行時我收到錯誤消息:操作矢量+ =失敗
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
我發現,這個消息是由cout << " a " << a << endl;
2引起的)沒有完成該cout << .....
操作但是一些垃圾被添加到this
而不是a的內容。
有什麼建議嗎?
爲什麼你使用't.end() - 1'?如果矢量爲空,則該值甚至不存在。 – jogojapan 2012-07-27 08:44:30
您是否嘗試過在調試器中運行?您應該能夠通過檢查回溯來看到導致此問題的線路。 – 2012-07-27 08:44:34
爲什麼你的運算符<<不適用於向量的const引用,而是向量對象? – ForEveR 2012-07-27 08:46:00