How to use friend operators in a template class? [duplicate]

筅森魡賤 提交于 2019-12-13 04:37:24

问题


I have template class which has some friend operators. The compiler complains about "friend declaration declares a non-template function". Unfortunately, I don't know how to resolve this error. Any hints?

The code looks as follows:

template<typename X> class Vect
{

protected:
    X v1_;
    X v2_;
    X v3_;

public:
    Vect( X v1, X v2, X v3 );
    Vect( const Vect<X> &v);
    ~Vect();
    void printVect( );
    friend ostream& operator<<(ostream& os, const Vect<X>& v);
    friend const Vect<X> operator*(Vect<X>& v, X n);
    friend const Vect<X> operator*(X n, Vect<X>& v);


};


template<typename X> Vect<X>::Vect( X v1, X v2, X v3 )
    : v1_(v1),v2_(v2), v3_(v3)  
{
//  v1_ = v1;
//  v2_ = v2;
//  v3_ = v3;  
}

template<typename X> Vect<X>::Vect( const Vect<X> &v )
    : v1_(v.v1_), v2_(v.v2_), v3_(v.v3_)
{
}

template<typename X> Vect<X>::~Vect( )
{
} 

template<typename X> void Vect<X>::printVect( )
{
    cout << "(" << v1_ << ", " << v2_ << ", " << v3_ << ")" << endl; 
}

template<typename X> ostream& operator<<(ostream& os, const Vect<X>& v)
{
    os << "(" << v.v1_ << ", " << v.v2_ << ", " << v.v3_ << ")" << endl;
    return os;
}

template<typename X> const Vect<X> operator*(Vect<X>& v, X n)
{
    Vect<X> tmp(v);
    tmp.v1_ *= n;
    tmp.v2_ *= n;
    tmp.v3_ *= n;
    return tmp;
}

template<typename X> const Vect<X> operator*(X n, Vect<X>& v)
{
    return v*n;
}

Thans in advance,

Jonas


回答1:


You need the template argument for the prototype:

template <typename T>
friend ostream& operator<<(ostream& os, const Vect<T>& v);


来源:https://stackoverflow.com/questions/19753609/how-to-use-friend-operators-in-a-template-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!