今天复习一下如何重载操作符,就编了如下程序:
搜了一下,发现那么输入输出流重载为什么不能在类内声明,类外实现呢??因为模板比较特殊,我们知道操作符重载函数不是类的成员函数,因此此处相当于定义了一个新的函数模板(不同于类中的friend ostream& operator<<(ostream& out,Test& t) )。但若去掉template ,函数中的参数Test就不知是什么类型,所以不能在模板类内声明,类外实现操作符重载。
#include
using namespace std;
template
class CPoint{
public:
CPoint(T a, T b): x(a),y(b)
{}
friend ostream & operator<<(ostream &os, const CPoint & p)
{
os<<’(’<<p.x<<’,’<<p.y<<’)’;
return os;
}
CPoint & operator=(const CPoint & p)
{
return p;
}
private:
T x;
T y;
};
int main(int argc, char *argv[])
{
CPoint a(1.2,3.5);
cout<<a;
}
作者:冬之晓东
来源:CSDN
原文:https://blog.csdn.net/qq_19528953/article/details/51200741
版权声明:本文为博主原创文章,转载请附上博文链接!