流运算符的重载

1.cout 是在iostream 中定义的,是ostream的对象

ostream& ostream::operator<<(int n)
{
    //
    return *this;
}
ostream& ostream::operator<<(const char* s)
{
    //
    return *this;
}

2.类似Java中重写String方法一样,C++中一般重载“<<”运算符,一般为重载为全局函数

Because:

对输出运算符的重载

 void operator<<(ostream& out) {    out << _year << "-" << _month << "-" << _day << endl; 

会出现一个问题,只能写成

d<<cout      //打印d中的年月日

因为函数的第一个参数是this指针,第二个参数才是我们传进去的 out,但是这与std中的cout使用习惯完全不符,我们的所打印变量是应该在cout的右边,如

  cout<<d<<endl

这样的重载和普通的函数没有两样,也就失去了重载函数的目的所在。

那么这样,我们便不可以把输出运算符的重载写成成员函数,写成成员函数去实现功能,能实现功能 但失去重载本身的意义。

那么我们在类外写重载函数,此时输出运算符的重载函数是一个全局的。

 3.例子

#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>

using namespace std;

class Complex
{
private:
    double real;
    double imag;
public:
    Complex(double r=0.0,double i=0.0):real(r),imag(i){}
    friend ostream& operator<<(ostream & os,const Complex& c);
    friend istream& operator>>(istream & is,const Complex& c);//起到声明friend作用,为全局函数做准备
};

ostream& operator<<(ostream& os,const Complex& c)
{
    os<<c.real<<'+'<<c.imag<<'i';
    return os;
}

iostream& operator>>(iostream& is,const Complex& c)
{
    string s;
    is>>s;
    int pos=s.find("+",0);
    string sTmp=s.substr(0,pos);
    c.real=atof(sTmp.c_str());
    sTmp=s.substr(pos+1,s.length()-pos-2);
    c.imag=atof(sTmp.c_str());
    return is;
}
原文地址:https://www.cnblogs.com/-Asurada-/p/10674249.html