如何在类模板中重载输入输出运算符和友元函数

来源:互联网 发布:南昌云迈网络做什么的 编辑:程序博客网 时间:2024/06/05 20:01

初学者对类模板中的重载输入输出运算符往往比较头疼,稍微不注意就会出错,并且很难掌握其用法

(注意:输入和输出函数只能以友元函数出现在类中)

(1)、如果是在普通类中重载输出运算符比较简单,下面给出一个具体的实例:

#include<iostream>
using namespace std;

class complex
{
    public:
        complex(){real=0;image=0;}
        complex(double r,double i){real=r;image=i;}
        friend ostream& operator <<  (ostream& output,complex& c);
    private:
        double real;
        double image;
};

ostream& operator << (ostream& output,complex& c)
{
    output<<"("<<c.real<<"+"<<c.image<<"i)"<<endl;
    return output;
}

int main()
{
    complex  c1(2,4);
    cout<<c1<<endl;
    return 0;
}

(2)、如果是在类模板中重载输出运算符,则需要在定义类之前声明重载重载输入运算符的语句,和一些特殊的格式;若不提前声明,编译时系统会显示“xx是类的私有成员,xx不能使用”的错误提示。下面用具体实例说明其应用方法:红色部分为特别注意的地方,套用下面的模板就能正确使用输出运算符在类模板中的重载

#include<iostream>
using namespace std;

//<<<<<<<<<<<<<<<<<<<<<<<<输入运算符重载的声明部分<<<<<<<<<<<<<<<<
template<class type>
ostream& operator << (ostream& output,complex<type>& c);

//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
template<class type>
class complex
{
    public:
        complex(){real=0;image=0;}
        complex(double r,double i){real=r;image=i;}
        //template<type>
        friend ostream& operator << <type> (ostream& output,complex& c);
    private:
        type real;
        type image;
};
template<class type>
ostream& operator << (ostream& output,complex<type>& c)
{
    output<<"("<<c.real<<"+"<<c.image<<"i)"<<endl;
    return output;
}

int main()
{
    complex<int> c1(2,4);
    cout<<c1<<endl;
    return 0;
}