模板类中重载<<和>>操作符

来源:互联网 发布:网络创世纪uo服务端 编辑:程序博客网 时间:2024/04/18 09:56

今天复习一下如何重载操作符,就编了如下程序:


搜了一下,发现那么输入输出流重载为什么不能在类内声明,类外实现呢??因为模板比较特殊,我们知道操作符重载函数不是类的成员函数,因此此处相当于定义了一个新的函数模板(不同于类中的friend ostream& operator<<(ostream& out,Test<T>& t) )。但若去掉template<class T> ,函数中的参数Test<T>就不知是什么类型,所以不能在模板类内声明,类外实现操作符重载。

#include <iostream>using namespace std;template <class T>class CPoint{public:    CPoint(T a, T b): x(a),y(b)    {}    friend ostream & operator<<(ostream &os, const CPoint<T> & p)    {        os<<'('<<p.x<<','<<p.y<<')';        return os;    }    CPoint<T> & operator=(const CPoint<T> & p)    {        return p;    }private:    T x;    T y;};int main(int argc, char *argv[]){    CPoint<float> a(1.2,3.5);    cout<<a;}


1 0
原创粉丝点击