0

我有模板类,其中有一些朋友运算符。编译器抱怨“朋友声明声明了一个非模板函数”。不幸的是,我不知道如何解决这个错误。有什么提示吗?

代码如下所示:

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;
}

比提前,

乔纳斯

4

1 回答 1

1

您需要原型的模板参数:

template <typename T>
friend ostream& operator<<(ostream& os, const Vect<T>& v);
于 2013-11-03T13:53:04.260 回答