提问者:小点点

重载多个类型的模板类运算符C++


我在surf.h中有以下代码,其中声明了一个具有两种不同类型的模板类:

using namespace std;    
template <typename T1, typename T2>

class surf;

template <typename T1, typename T2>
ostream & operator << (ostream & str, surf<T1,T2> & ov);

template <typename T1, typename T2>
class surf
{
public:
    surf(T1 v1, T2 v2):
    v1_(v1),
    v2_(v2)
    {}

    friend ostream & operator << <T1, T2> (ostream & str, surf<T1,T2> & ov);

    T1 v1_;
    T2 v2_;

};

template <typename T1, typename T2>
ostream & operator << (ostream & str, surf<T1,T2> & ov)
{
    str << "("<<ov.v1_<<","<<ov.v2_<<")";
    return str;
}

typedef surf<int,double> intSurf;

然后定义一个新类,其中创建了一个类型为T的向量(在field.h中)

   template<typename T>
class field;

template<typename T>
ostream & operator << (ostream & str, const field<T> & ov);

template<typename T>
class field
{
public:

    field( int n, T val):
        f_(n,val)
        {}

    friend ostream & operator << <T> (ostream & str, const field<T> & ov);
protected:

    vector<T> f_;
};

template<typename T>
ostream & operator << (ostream & str, const field<T> & ov)
{
    for(auto &fE: ov.f_)
    {
        str << fE << endl;
    }
    return str;
}

typedef field<intSurf> surfField;

在main.cpp中,我使用了这个字段。

#include "field.h"

int main()
{

    surfField a(4, intSurf(2,5));   

    cout<< a << endl;

    return true;
}

我用G++(版本5.4)编译它,得到以下错误:

从main.cpp:2:0:field.h:在“std::ostream&operator<<(std::ostream&,const field&)[with T=surf;std::ostream=std::basic_ostream]”的实例化中:main.cpp:9:9:需要从here field.h:36:7:错误:与“operator<<”(操作数类型为“std::ostream{又名std::basic_ostream}”和“const surf”)不匹配)str<

我在做什么?


共1个答案

匿名用户

您的运算符<<重载缺少常量

template <typename T1, typename T2>
ostream & operator << (ostream & str, const surf<T1,T2> & ov);
//                                    ^^^^^
//...
friend ostream & operator << <T1, T2> (ostream & str, const surf<T1,T2> & ov);
//                                                    ^^^^^
//...
template <typename T1, typename T2>
ostream & operator << (ostream & str, const surf<T1,T2> & ov)
//                                    ^^^^^
//...

需要此常量,因为您试图显示来自常量字段&ov的元素

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(重载|多个|类型|模板|类|运算符|c++)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?