尝试重载"<<"时出现语法错误:参数太多

vvM*_*Ovv 1 c++ ostream

我一直在寻找一段时间,最接近答案的就是那边

C++中的toString覆盖

但是我无法在班上工作.

我有一个Table2D.h包含这个:

std::string toString() const;
std::ostream & operator<<( std::ostream & o, const Table2D<T> & s );
Run Code Online (Sandbox Code Playgroud)

我有一个模板类Table2D.template,其中包含:

template <class T>
std::ostream & :: operator<<( std::ostream & o, const Table2D<T> & s ){
    return out << s.toString();
}
Run Code Online (Sandbox Code Playgroud)

当我从main调用我的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
Run Code Online (Sandbox Code Playgroud)

只是让你知道第59行包含

for (unsigned y=0; y<m_height; y++) col_ptr[y] = (T) col_ptr_src[y];
Run Code Online (Sandbox Code Playgroud)

正如你所看到的那样包含没有<<,所以我不完全确定它是指什么.


编辑:

从类中删除声明后,我用它替换了头文件中的条目

template <class T>
std::ostream& operator<<( std::ostream& o, const Table2D<T>& s ) {
    return o << s.toString();
}
Run Code Online (Sandbox Code Playgroud)

并得到以下错误:

Table2D.h(60): error C2804: binary 'operator <<' has too many parameters
Table2D.h(89) : see reference to class template instantiation 'Table2D<T>' being compiled
Run Code Online (Sandbox Code Playgroud)

模板文件中的第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();
}
Run Code Online (Sandbox Code Playgroud)

Set*_*gie 5

除了你的语法错误1,operator<<其他类(ostream在这种情况下)的重载必须是非成员函数.将您的定义更改为

template <class T>
std::ostream& operator<<( std::ostream& o, const Table2D<T>& s ) {
    return o << s.toString();
}
Run Code Online (Sandbox Code Playgroud)

并完全从类中删除它的声明,以便它是一个自由函数.


1如果你想知道原因,成员函数二元运算符只接受一个参数,因为左边是调用对象,通过访问this.另外,你忘了定义Table2D<T>之前的::那个.但是即使你修复了它们也不会按预期工作,因为如前所述,其他类的操作符重载必须通过自由函数完成.