如何在模板类中使用好友运算符? [英] How to use friend operators in a template class?

查看:70
本文介绍了如何在模板类中使用好友运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有一些朋友运算符的模板类.编译器抱怨朋友声明声明一个非模板函数".不幸的是,我不知道如何解决此错误.有提示吗?

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?

代码如下:

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

先谢谢

乔纳斯(Jonas)

推荐答案

您需要原型的模板参数:

You need the template argument for the prototype:

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

这篇关于如何在模板类中使用好友运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆