我一直在寻找了一段时间,在最接近的答案是在那里语法错误时,试图重载“<<”:
参数太多但是我没能让它在我的课堂上工作。
我有一个Table2D.h
其中包含此:
std::string toString() const;
std::ostream & operator<<(std::ostream & o, const Table2D<T> & s);
,我有一个模板类Table2D.template
其中包含此:
template <class T>
std::ostream & :: operator<<(std::ostream & o, const Table2D<T> & s){
return out << s.toString();
}
,当我打电话给我的toString()从主,它的功能函数正确。 但是,当我使用std::cout
调用<<
运算符时,出现以下错误。
Table2D.h(59): error C2804: binary 'operator <<' has too many parameters
Table2D.h(85) : see reference to class template instantiation 'Table2D<T>' being compiled
Table2D.template(100): error C2039: '<<' : is not a member of '`global namespace''
Table2D.h(59): error C2804: binary 'operator <<' has too many parameters
只是让你知道59'th行包含
for (unsigned y=0; y<m_height; y++) col_ptr[y] = (T) col_ptr_src[y];
正如你看到不包含<<
的,所以我不完全肯定什么它引用。
编辑:
从类移除声明之后,我取代它与这个
template <class T>
std::ostream& operator<<(std::ostream& o, const Table2D<T>& s) {
return o << s.toString();
}
在头文件条目,并得到了以下错误:
Table2D.h(60): error C2804: binary 'operator <<' has too many parameters
Table2D.h(89) : see reference to class template instantiation 'Table2D<T>' being compiled
第89行模板文件中包含std::stringstream resultStream;
这是我的ToString函数的第一行,它看起来像这样
template <class T>
std::string Table2D<T> :: toString() const{
std::stringstream resultStream;
for(unsigned i = 0; i< m_height; i++){
for (unsigned j = 0; j < m_width; j++){
resultStream << (*this)[i][j] << "\t";
}
resultStream << endl;
}
return resultStream.str();
}
thank's @pst我在使用C++识别错误时遇到了很多麻烦,所以我的问题名称可能有点偏离。再次感谢。 – vvMINOvv
如果您不知道,请点击页面左上角红色圈出的数字,通过@ -symbol查看针对您的评论。如果你愿意,我会在你的回答中看到我对你的评论。 –