模板类运算符重载多个类型名称C.

loading...


1

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

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&)[带T = surf; std :: ostream = std :: basic_ostream]':main.cpp:9:9:从这里需要field.h:36:7:错误:'operator <<'不匹配(操作数类型是'std :: ostream '和'const surf')str << fE << endl;

我在做什么?

1回答

  • 2

    您错过了 const ,因为您的过载 operator <<

    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)
    //                                    ^^^^^
    //...
    

    这个const是必需的,因为你试图显示来自 const field<T> & ov 的元素

loading...

评论

暂时没有评论!